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

时间:2013-03-12 14:47:16

标签: linq nhibernate

我有一个包含4个字段的数据库,如下所示:

ID      DeviceId       Location        Date
1           A             ...            2
2           A             ...            1
3           B             ...            2

对于每个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();

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

select loc

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

3 个答案:

答案 0 :(得分:7)

我猜您必须使用GroupByTake的某种组合。试试这个,

var distinctDeviceIdsByDate = 
    locations.OrderByDescending(location => location.DeviceId)
             .ThenByDescending(location => location.Date)
             .GroupBy(location => location.DeviceId)
             .SelectMany(location => location.Take(1));

答案 1 :(得分:1)

假设每个Date DeviceId是唯一的,您可以尝试

//Get the latest used unique deviceId's
var distinctDeviceIdsByDate = (
      from loc in Session.Query<Location>()
      group loc by loc.DeviceId
      into g
      select new
      {
          DeviceID = g.Key,  
          Location = g.OrderByDescending(l => l.Date).First().Location;
      };

答案 2 :(得分:0)

您可以使用分组来解决此问题。

var locations = new [] {
    new { DeviceId = "A", Date = 2, Location = ".." },
    new { DeviceId = "A", Date = 1, Location = ".." },
    new { DeviceId = "B", Date = 2, Location = "...." },
};

var lastUsedLocations = 
    from l in locations
    group l by l.DeviceId into g
    let lastUsed = g.OrderBy(x => x.Date).Last()
    select lastUsed;

// lastUsedLocations contains
// DeviceId       Date        Location
// A              2           ..
// B              2           ....