最有效的方法是从集合中移除n个元素并将这些已移除的元素添加到另一个已存在的集合中,这两个集合不同。
目前我有以下代码:
var entries = collection.Take(5).ToList();
foreach(var entry in entries)
collection.Remove(entry);
otherCollection.AddRange(entries);
然而,对我来说,这看起来并不高效(多个线性算法而不是只有一个)。
一种可能的解决方案当然可以改变集合实现方式-只要满足以下要求:
otherCollection
必须实现IEnumerable<T>
,当前为List<T>
类型。collection
必须实现ICollection<T>
,当前为LinkedList<T>
类型。
Equals()
或 GetHashCode()
。最有效的方法是什么?
由于我的性能考虑显然太难理解了,所以这里再次展示我的代码示例:
var entries = collection.Take(1000).ToList(); // 1000 steps
foreach(var entry in entries) // 1000 * 1 steps (as Remove finds the element always immediately at the beginning)
collection.Remove(entry);
otherCollection.AddRange(entries); // another 1000 steps
总共有3000个步骤 => 我想将其减少为1000个步骤。
IEnumerable<T>
上的扩展方法是有意设计成这样的。 - evanmcdonnal