Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 获取实体框架中按不同属性分组的最新项的列表_C#_Entity Framework - Fatal编程技术网

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());
但是,我犯了这个错误
无法转换orderbydescending

GroupBy的结果是一个隐式键+集合。实际上,它有很多“味道”,可以做一些微妙不同的事情。要获得这样的结果,您需要的是
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.