6

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

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

对于每个DeviceId我想要从最高日期的记录中获得的位置。我可以得到 distinctDeviceId是这样的:

// 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's 之外我无法获得任何东西,因此无法确定要选择哪些行。如果我尝试选择以下内容:

select loc

我只能得到所有列的唯一组合的行。我确信有一个简单的解决方案,但恐怕我现在无法弄清楚。

4

3 回答 3

7

我猜你必须使用GroupBy和的某种组合Take。试试这个,

var distinctDeviceIdsByDate = 
    locations.OrderByDescending(location => location.DeviceId)
             .ThenByDescending(location => location.Date)
             .GroupBy(location => location.DeviceId)
             .SelectMany(location => location.Take(1));
于 2013-03-12T14:59:29.467 回答
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;
      };
于 2013-03-12T15:01:55.320 回答
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           ....
于 2013-03-12T15:01:47.780 回答