从集合中删除 n 个元素并将这些删除的 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 步。
最佳答案
前面的函数只返回一半的结果。你应该使用:
public static IEnumerable<T> TakeAndRemove<T>(Queue<T> queue, int count)
{
for (int i = 0; i < count && queue.Count > 0; i++)
yield return queue.Dequeue();
}
关于c# - 从集合中获取和删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18600891/