Take&;从集合中删除元素

本文关键字:删除 元素 集合 amp Take | 更新日期: 2023-09-27 18:30:01

从集合中删除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步。

Take&;从集合中删除元素

前面的函数只返回一半的结果。您应该使用:

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();
}

在您的用例中,最好的数据结构似乎是队列。当使用队列时,您的方法可以如下所示:

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();
}