Linq从组中选择唯一项目,并按ID获取类似项目

时间:2016-09-23 14:41:56

标签: c# .net linq

var groups = db.Orders.GroupBy(x => x.OwnedOn);

假设群体返回以下结果:
第1组:

[0] ID = 3      Name = "Uncharted 4"           OwnerID = 1    Owned On 21/08/2016
[1] ID = 6      Name = "Assassin's Creed"      OwnerID = 3    Owned On 21/08/2016
[2] ID = 4      Name = "Tomb Raider"           OwnerID = 2    Owned On 21/08/2016

第2组:

[0] ID = 5      Name = "Assassin's Creed"      OwnerID = 7    Owned On 22/08/2016

第3组:

[0] ID = 21     Name = "FIFA 17"               OwnerID = 10    Owned On 23/08/2016
[1] ID = 12     Name = "Crash Bandicoot"       OwnerID = 5    Owned On 23/08/2016

确定。现在我想执行一个Linq,它会给每个具有最高OwnerID的组中的一个项目。 所以预期的结果将是:

[0] ID = 6      Name = "Assassin's Creed"      OwnerID = 3    Owned On 21/08/2016
[1] ID = 5      Name = "Assassin's Creed"      OwnerID = 7    Owned On 22/08/2016
[2] ID = 21     Name = "FIFA 17"               OwnerID = 10    Owned On 23/08/2016

1 个答案:

答案 0 :(得分:5)

这样的事情可以胜任这项工作,我相信:

db.Orders.GroupBy(x => x.OwnedOn)
         .Select(grp => grp.OrderByDescending(e => e.OwnerID).First());

.NET Fiddle