从列表中删除匹配项的更好方法

gil*_*rtc 2 c# list

在c#中,当我想从列表中删除一些项目时,我会按以下方式执行此操作,

List<Item> itemsToBeRemoved = new List<Item>();
foreach(Item item in myList)
{
   if (IsMatching(item)) itemsToBeRemoved.Add(item);
}

foreach(Item item in itemsToBeRemoved)
{
   myList.Remove(item);
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法呢?

Eri*_*ert 21

好吧,你可以调用完全符合你想要的方法.

myList.RemoveAll(IsMatching);
Run Code Online (Sandbox Code Playgroud)

通常,使用完全符合您想要的方法而不是自己重新发明它的方法"更好".


Bra*_*don 12

myList.RemoveAll(x=> IsMatching(x));
Run Code Online (Sandbox Code Playgroud)

  • 如果你愿意,你甚至不必使用lambda.编译器会自动将"IsMatching"转换为Predicate <T>. (5认同)