gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 03:05:07 25 4
gpt4 key购买 nike

<分区>

我需要遍历 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(...) ,因为循环内有大量代码,先于条件。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com