Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 495
abatishchev Avatar asked Dec 18 '25 04:12

abatishchev


1 Answers

How about:

data.RemoveAll(condition);

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

like image 87
Jon Skeet Avatar answered Dec 20 '25 18:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!