Search code examples
c#linqlinqpad

How to use LINQ methods like Max(), First(), and OrderBy() in LINQPad?


I'm trying to do a C# statement in LINQPad like this:

var result = 
    from tv in TankValues 
    join t in Tanks on tv.TankID equals t.ID
    orderby t.Description, tv.LogDate descending  
    select new {
        Description = t.Description,
        LogDate = tv.Max(l => l.LogDate),
        Level = tv.LevelPercentTotal
    };

result.Dump();

But I keep getting an error:

'LINQPad.User.TankValues' does not contain a definition for 'Max' and no 
extension method 'Max' accepting a first argument of type 
'LINQPad.User.TankValues' could be found (press F4 to add a using 
directive or assembly reference)

I pressed F4 and added every reference with "LINQ" in the name, and still no luck.


Solution

  • I'm trying to get the most recent TankValue record for each tank.

    var result = 
        from t in Tanks
        join tv in TankValues on t.ID equals tv.TankID
        group tv by new { t.ID, t.Description } into g
        orderby g.Key.Description descending  
        select new {
            Description = g.Key.Description,
            LogDate = g.OrderByDescending(x => x.LogDate).FirstOrDefault(),
            Level = g.OrderByDescending(x => x.LogDate).FirstOrDefault().LevelPercentTotal
        };