Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 拿&;从集合中删除元素_C#_.net_Linq_Collections_Time Complexity - Fatal编程技术网

C# 拿&;从集合中删除元素

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); 然而,在我看来,这一点性能都不好(多个线性算法而不是一个) 当然,一个可能的解决方案可能会改变收集实现—只要满足以下要求

从集合中删除n个元素并将这些删除的n个元素添加到已存在的不同集合中,最有效的方法是什么

目前,我有:

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不是一个单词。