C# 获取实体框架中按不同属性分组的最新项的列表
我有一个实体框架实体C# 获取实体框架中按不同属性分组的最新项的列表,c#,entity-framework,C#,Entity Framework,我有一个实体框架实体Shoe,它与另一个实体Person有一对多的关系。每个人都有许多鞋子。我想得到每个人最新的鞋子清单 public class Shoe { public Long PersonId { get; set; } public DateTime PurchaseDate { get; set; } } 我试过这个: var latestShoesPerPerson = _dbContext.Shoe .GroupBy(shoe => shoe.Per
Shoe
,它与另一个实体Person
有一对多的关系。每个人都有许多鞋子。我想得到每个人最新的鞋子清单
public class Shoe {
public Long PersonId { get; set; }
public DateTime PurchaseDate { get; set; }
}
我试过这个:
var latestShoesPerPerson = _dbContext.Shoe
.GroupBy(shoe => shoe.PersonId)
.Select(shoes => shoes.OrderByDescending(shoe => shoe.PurchaseDate).First());
但是,我犯了这个错误
无法转换orderbydescendingGroupBy的结果是一个隐式键+集合。实际上,它有很多“味道”,可以做一些微妙不同的事情。要获得这样的结果,您需要的是
GroupBy(IEnumerable,Func,Func)
使用此选项,表达式看起来更像:
var latestShoesPerPerson = _dbContext.Shoe
.GroupBy(shoe => shoe.PersonId, (personId, shoes) => shoes.OrderByDescending(s => s.PurchaseDate).FirstOrDefault())
.ToList(); // list of the earliest shoe for each person.