Most reliable way to clean List<T> depending on Predicate<T>

I have List<T> data and Predicate<T> condition.

What way should I use to clear data depending on condition result?

  • Option 1:

    var del = data.Where(i => condition);
    data.RemoveAll(i => del.Contains(i));
    
  • Option 2:

    var del = data.Where(i => condition);
    for (int i = 0; i < del.Count; i++)
        data.Remove(del[i]);
    
  • Option 3:

    var del = data.Where(i => condition);
    foreach (var i in del)
       data.Remove(i);
    
  • Option 4:

    data = data.Where(i => !condition);
    
  • Any other?

Answers


How about:

data.RemoveAll(condition);

Note that your fourth option won't work without a call to ToList().


Need Your Help

EF Object entity State moves to Unchanged when attached to new Context

linq entity-framework save

I have go the oddest problem, I get an object from EF and pass it back to the Business Logic for manipulation, when finished i'm trying to save the object back to the DB, when the object is passed ...

Runtime safety for Arrays vs Collections in Java

java arrays generics arraylist collections

Collections do not provide runtime safety, they only provide compile time safety.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.