使用LINQ选择具有不同列值的所有行

dan*_*130 6 linq nhibernate

我有一个包含4个字段的数据库,看起来像这样:

ID      DeviceId       Location        Date
1           A             ...            2
2           A             ...            1
3           B             ...            2
Run Code Online (Sandbox Code Playgroud)

对于每个DeviceId我想要具有最高日期的记录的位置.我可以得到DeviceId像这样的明显:

// get all locations
var locations = Session.Query<Location>().ToList();

//Get the latest used unique deviceId's
var distinctDeviceIdsByDate = (
      from loc in locations
      orderby loc.DeviceId, loc.Date descending
      select loc.DeviceId).Distinct().ToList();
Run Code Online (Sandbox Code Playgroud)

然后我会使用join来获取所需的行,但这不会有任何好处,因为我无法得到除了之外的任何东西DeviceId,因此无法识别要选择的行.如果我尝试选择以下内容:

select loc
Run Code Online (Sandbox Code Playgroud)

我只能获得具有所有列的唯一组合的行.我确信这是一个简单的解决方案,但我恐怕现在无法理解.

Dot*_*ala 7

我想你必须使用一些组合GroupByTake.试试这个,

var distinctDeviceIdsByDate = 
    locations.OrderByDescending(location => location.DeviceId)
             .ThenByDescending(location => location.Date)
             .GroupBy(location => location.DeviceId)
             .SelectMany(location => location.Take(1));
Run Code Online (Sandbox Code Playgroud)