C# 拿&;从集合中删除元素
从集合中删除n个元素并将这些删除的n个元素添加到已存在的不同集合中,最有效的方法是什么 目前,我有:C# 拿&;从集合中删除元素,c#,.net,linq,collections,time-complexity,C#,.net,Linq,Collections,Time Complexity,从集合中删除n个元素并将这些删除的n个元素添加到已存在的不同集合中,最有效的方法是什么 目前,我有: var entries = collection.Take(5).ToList(); foreach(var entry in entries) collection.Remove(entry); otherCollection.AddRange(entries); 然而,在我看来,这一点性能都不好(多个线性算法而不是一个) 当然,一个可能的解决方案可能会改变收集实现—只要满足以下要求
var entries = collection.Take(5).ToList();
foreach(var entry in entries)
collection.Remove(entry);
otherCollection.AddRange(entries);
然而,在我看来,这一点性能都不好(多个线性算法而不是一个)
当然,一个可能的解决方案可能会改变收集实现—只要满足以下要求:
必须实现otherCollection
,它当前的类型是IEnumerable
List
必须实现collection
,它当前的类型是ICollection
LinkedList
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)
{
count = Math.Min(queue.Count, count);
for (int i = 0; i < count; i++)
yield return queue.Dequeue();
}
公共静态IEnumerable TakeAndRemove(队列,整数计数)
{
count=Math.Min(queue.count,count);
for(int i=0;i
上一个函数只返回一半结果。你应使用:
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();
}
公共静态IEnumerable TakeAndRemove(队列,整数计数)
{
对于(int i=0;i0;i++)
让出返回队列。退出();
}
你总是用O(n)操作进行线性搜索,而集合没有更好的方法。我认为集合有一个RemoveAll(collection.Take(5))@TimSchmelter:这与集合或非线性搜索无关。它是关于如何避免多个O(n)操作。查看我的代码示例@杰罗恩万兰根:哪一套?当前typeof(collection)是LinkedList,它不支持RemoveAll()
Performant不是一个单词。