c# - 从集合中获取和删除元素

标签 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);

但是,这对我来说一点都不高效(多个线性算法,而不是只有一个)。

一个可能的解决方案当然可以更改集合实现 - 只要满足以下要求:

  • 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/

相关文章:

c# - C# .NET 中通过 HTTP 发布的 SOAP 对象

performance - LINQ 比简单循环慢很多吗?

c# - MoreLINQ 的 DistinctBy 和 Linq 的 GroupBy 有什么区别

.net - 将旧版 VB6 函数调用转换为 .NET 的实用程序

c# - 如何在 C++/CLI 中将事件处理程序分配给事件?

c# - 如何将 IEnumerable<object> 转换为 List<IFoo>,其中每个对象都是一个 IFoo?

c# - Linq 到实体 : Left Join and filter

c# - 在 3 个逗号后添加换行符

c# - 如何让IE8识别文件下载名称?

c# - 单击不同按钮时保持对文本框的关注