PaulBinCT2 PaulBinCT2 - 2 months ago 6x
C# Question

Rearranging the clauses in my LINQ?

Sigh... On my tombstone it will say "Died adding one more clause to a LINQ query"

So I have the following:

var validStatuses = new[] {
"Assigned", "Donor Called", "Dispatched", "Waiting",
"Title Rec'd", "Sending Title", "Cancelled", "Waiting"};

var ud = db.Updates
.Where(c => !c.Sold && validStatuses.Contains(c.Status))
.GroupBy(c => c.Vehicle)
.Select(x => x
.OrderByDescending(y => y.TimeStamp)

And I have realized that I need to have the Contains clause after the date. In other words, I need to select the most recent entry only if that most recent entry Contains "validStatuses". Right now it will return multiple entries as long as each one contains "validStatuses".

I'd be deeply indebted for assistance... thank you!


My understanding is that this could work (but I missed the latest comments...):

var ud = db.Updates
              .Where(c => !c.Sold)
              .GroupBy(c => c.Vehicle, x => x, (x,gr) => new { key = x,
                  list = gr.ToList().OrderByDescending(z => z.TimeStamp).First() })
               .Where(x=> validStatuses.Contains(x.list.Status))
              .Select(x => x.list).ToList();

It is a grouping by vehicle and it is preserving only the groups where the most recent item has a valid status...