Skip to main content
 首页 » 编程设计

c#之从集合中移除对象

2024年01月21日34lonelyxmas

我有一个对象集合,我希望根据返回 true 或 false 的函数调用从中删除一些对象。请参阅下面的示例代码片段 -

for each(MyClass obj in Objects) 
{ 
  if(!ValidateObject(obj) 
  { Objects.Remove(obj); } 
} 

我不想在这里使用循环。以上示例需要一个类轮代码。 提前致谢。

请您参考如下方法:

RemoveAll如果您使用的是列表,则可以使用带有谓词的方法

public int RemoveAll( 
    Predicate<T> match 
) 

The Predicate(Of T) delegate that defines the conditions of the elements to remove.

 List<MyClass > f = new List<MyClass >(); 
 f.RemoveAll(x => ! ValidateObject(x) );