0

I'm trying to remove all records in a List<T> matching a where condition. What I did find in linq is the RemoveAll() method but it seems to only work by removing properties matching a condition instead of the complete row in the list.

So I did try a remove all as suggested here in conjunction with a Where clause which causes an "argument null exception".

Question:

How can you RemoveAll list rows matching a condition using linq?

//Sort the list by the UpdatedTime time descending
//Remove all records in list that are older than today's date and status equal to BB. Then order the remaining records desc.
var cuttOff = DateTime.UtcNow.AddDays(-10);
List<Escalation> escHistorySorted = escHistory.RemoveAll.Where(x => x.UpdatedTime  <= cuttOff && x.status == "BB").OrderByDescending(d => d.UpdatedTime).ToList();
Community
  • 1
  • 1
Brian Var
  • 6,029
  • 25
  • 114
  • 212
  • 1
    **Invert the condition** ? So, **List escHistorySorted = escHistory.Where(x => !(x.UpdatedTime <= cuttOff && x.status == "BB"))** . Or maybe I didn't get what you are asking here :) . – MrClan Aug 24 '16 at 10:34

1 Answers1

2

It looks like you're trying to do too much at once.

Remove the records first (move the predicate from your where clause directly inside RemoveAll), and then sort them.

var cuttOff = DateTime.UtcNow.AddDays(-10);

escHistory.RemoveAll(x => x.UpdatedTime <= cuttOff && x.status == "BB");

List<Escalation> escHistorySorted = escHistory.OrderByDescending(d => d.UpdatedTime).ToList();

The return value of RemoveAll is an integer representing the number of records removed, so you can't simply order the result of calling that method.

Grant Winney
  • 65,241
  • 13
  • 115
  • 165