Linq,选择按容器分组的第一个过期记录的列表

时间:2016-02-22 18:17:44

标签: c# linq

我有一张桌子看起来像这样的水果:

FruitID | BasketID | ExpirationDate | OtherColumns

一篮子包含许多水果,其中一些水果已经过期。我正在编写一个查询,该查询返回所有记录的列表,其中BasketID的{​​{1}} FruitID大于UtcNow。这就是我所拥有的,但我正在努力与该组的选择:

ExpirationDate

我确定我不远,但我无法弄明白。我需要改变什么?

2 个答案:

答案 0 :(得分:1)

对于每个购物篮,您可以使用此查询使用最过期的水果创建MyModel对象:

List<MyModel> TheExpiredFruits = (from b in MyDC.Fruits
                                  where b.ExpirationDate < DateTime.UtcNow
                                  group b by b.BasketID into fruits
                                  let fruit = fruits.OrderByDescending(f => f.ExpirationDate).First()
                                  select new MyModel()
                                  {
                                      BasketId = fruit.BasketID,
                                      Column1 = fruit.SomeColumn1,
                                      ColumnN = fruit.SomeColumnN,
                                  }).ToList();

答案 1 :(得分:1)

要显示有关最近过期水果的详细信息,您需要以下内容:

var today = DateTime.UtcNow.Date; // lock in UTC date so it doesn't vary during the query
var result = MyDB.Fruits
    .Where(x => x.ExpirationDate < today)
    .OrderBy(x => x.ExpirationDate)
    .GroupBy(x => x.BasketID, (key, items) => new
    {
        BasketID = key,
        MostRecentlyExpiredFruit = items.Last()
    })
    .Select(x => new MyModel
    {
        BasketID = x.BasketID,
        MostRecentlyExpiredFruitID = x.MostRecentlyExpiredFruit.FruitID,
        MostRecentlyExpiredFruitName = x.MostRecentlyExpiredFruit.Name,
        HowLongSinceMostRecentExpiration =
            today - x.MostRecentlyExpiredFruit.ExpirationDate
    });

在查询语法中:

var today = DateTime.UtcNow.Date; // lock in UTC date so it doesn't vary during the query
var result =
    from f in MyDC.Fruits
    orderby f.ExpirationDate
    where f.ExpirationDate < today
    group f by f.BasketID into basket
    let summary = new
    {
       BasketID = basket.Key,
       MostRecentlyExpiredFruit = basket.Last()
    }
    select new MyModel
    {
        BasketID = summary.BasketID,
        MostRecentlyExpiredFruitID = summary.MostRecentlyExpiredFruit.FruitID,
        MostRecentlyExpiredFruitName = summary.MostRecentlyExpiredFruit.Name,
        HowLongSinceMostRecentExpiration =
            today - summary.MostRecentlyExpiredFruit.ExpirationDate
    };