c# - 遍历列表并从中删除项目的最佳方法?

标签 c# list iteration

<分区>

我需要遍历 List<myObject>并删除满足特定条件的项目。

我看到了这个答案(https://stackoverflow.com/a/1582317/5077434):

Iterate your list in reverse with a for loop:

for (int i = safePendingList.Count - 1; i >= 0; i--)
{
    // some code
    // safePendingList.RemoveAt(i);
}

Example:

var list = new List<int>(Enumerable.Range(1, 10));
for (int i = list.Count - 1; i >= 0; i--)
{
    if (list[i] > 5)
      list.RemoveAt(i);
}
list.ForEach(i => Console.WriteLine(i));

但我明白for效率低于 foreach ,

所以我想到了使用后者如下:

foreach (var item in myList.ToList())
{
    // if certain condition applies:
    myList.Remove(item)
}

一种方法比另一种更好吗?

编辑:

我不想使用 RemoveAll(...) ,因为循环内有大量代码,先于条件。

最佳答案

不管你愿不愿意,你都必须循环遍历列表,for 循环是最有效的循环:

  for (int i = safePendingList.Count - 1; i >= 0; --i) 
    if (condition)
      safePendingList.RemoveAt(i);

如果你想删除范围(而不是整个列表),只需修改for循环:

  // No Enumarable.Range(1, 10) - put them into "for"
  for (int i = Math.Min(11, safePendingList.Count - 1); i >= 1; --i)
    if (condition)
      safePendingList.RemoveAt(i); 

或者如果您必须在正向循环中删除项目:

  for (int i = 0; i < safePendingList.Count;) // notice ++i abscence
    if (condition)
      safePendingList.RemoveAt(i);
    else
      i += 1; // ++i should be here

相反,safePendingList.ToList() 创建初始 safePendingList副本,这意味着内存CPU 开销:

  // safePendingList.ToList() - CPU and Memory overhead (copying)
  foreach (var item in safePendingList.ToList()) {
    if (condition)
      myList.Remove(item); // Overhead: searching
  }

但是,在许多情况下,最合理的计划就是让 .Net 为您工作:

  safePendingList.RemoveAll(item => condition);

关于c# - 遍历列表并从中删除项目的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36690098/

相关文章:

python - 组合功能

Java泛型调用构造函数

javascript - 反转字符串 : Recursion vs iteration in javascript

c# - 如何在 rdlc c# 报告中使用多个数据集

c# - 为什么我不能将 Debug.Assert() 与接受动态并返回 bool 的方法一起使用?

c# - 在 WinRT/C# 中通过 StreamSocket 连接到 IMAP

c# - 每个类(class)的唯一ID

c# - 使用 linq 检查字符串值是否在字符串数组或 C# 中的列表中

c - 递归函数到迭代,该函数给定 g(n) = 2*g(n-1)+3*g(n-2)

python - 运行时错误: dictionary changed size during iteration in python