Linq:从其他组中选择第一项

时间:2012-05-14 18:32:38

标签: linq

我正在尝试编写一个查询来查找该组中的一个项目,其中按行业和权重进行分组,然后从这一项我必须得到权重最大且余额也是最大值 这是一个例子:

var data = new[] {
new {ID = 1, Industry = 2, Weight = 2, Balance = 500}, 
new {ID = 2, Industry = 2, Weight = 2, Balance = 300}, 
new {ID = 3, Industry = 2, Weight = 1, Balance = 100},
new {ID = 5, Industry = 4, Weight = 1, Balance = 100}, 
new {ID = 6, Industry = 4, Weight = 2, Balance = 150}, 
new {ID = 7, Industry = 4, Weight = 1, Balance = 300},
};

var res = from a in data group a by new {a.Industry, a.Weight} into g
let ID = g.First().ID
let Balance = g.Max(a => a.Balance)
select new { ID, g.Key.Industry, g.Key.Weight, Balance};
Console.WriteLine(res);

因此,结果我应该得到两个记录

ID   Industry   Weight   Balance
1      2           2      500
6      4           2      150

但是通过上面的查询,我得到了4条记录 有什么建议吗?

此致 德米特里

2 个答案:

答案 0 :(得分:0)

可能有许多不同的解决方案,但只有一个是按行业分组,并根据您的“第一个要素选择”标准对每个组进行排序,然后选择每个组中的第一个项目。

var res = from item in data
    group item by item.Industry into g
    let first = g.OrderByDescending(x => x.Weight)
                  .ThenByDescending(x => x.Balance).First()
    select first;

答案 1 :(得分:0)

data.GroupBy(x=>new {x.Industry,x.Weight})
    .ToDictionary(y=>y.Key,y=>y.ToList().Max(x=>x.Balance));

如果您不想要字典,那么您也可以选择新的DTO或动态对象,如下所示:

data.GroupBy(x=>new {x.Industry,x.Weight})
    .Select(x=>new {x.Key.Industry,x.Key.Weight,x.ToList().Max(y=>y.Balance)});

希望这就是你所需要的。