如何在LINQPad中使用LINQ方法,如Max(),First()和OrderBy()?

时间:2013-12-19 17:37:13

标签: c# linq linqpad

我正在尝试在LINQPad中执行C#语句,如下所示:

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();

但我一直收到错误:

'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)

我按下F4并在名称中添加了每个带有“LINQ”的引用,但仍然没有运气。

2 个答案:

答案 0 :(得分:0)

你可以在一些基本上有一堆实体的IQueryable个对象上使用它们,你不能直接在实体本身上应用它们。

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.MaxDate,// or TankValues.Max(x=>x.LogDate) // if you need max date here
        Level = tv.LevelPercentTotal
    }).Max(l => l.LogDate)//This is just to show that Max works here;

result.Dump();

答案 1 :(得分:0)

  

我正在尝试获取每个坦克的最新TankValue记录。

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
    };