我需要遍历 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);