我需要一个linq查询来获取唯一的对象列表,按Dep分组它们并获得具有最高进度的值。 我有一个对象列表,如下所示:
List<SomeObjects> lstObjects:
lstObjects[0] - Dep: Marketing Comp:ABC Progress: 1
lstObjects[1] - Dep: Sales Comp:ABC Progress: 2
lstObjects[2] - Dep: Marketing Comp:DEF Progress: 2
lstObjects[3] - Dep: Marketing Comp:DEF Progress: 3
lstObjects[4] - Dep: Sales Comp:ABC Progress: 1
lstObjects[5] - Dep: Marketing Comp:ABC Progress: 2
lstObjects[6] - Dep: Marketing Comp:ABC Progress: 1
lstObjects[7] - Dep: Marketing Comp:ABC Progress: 1
正如你所见,Dep:Marketing Comp:ABC,用不同的进展重复自己:我必须获得具有最高进度的唯一对象列表。
Eg: lstObjects[0] - Dep: Marketing Comp:ABC Progress: 1
lstObjects[5] - Dep: Marketing Comp:ABC Progress: 2
Here I should get, lstObjects[5] - Dep: Marketing Comp:ABC Progress: 2
In, lstObjects[2] - Dep: Marketing Comp:DEF Progress: 2
lstObjects[3] - Dep: Marketing Comp:DEF Progress: 3
In this I should get lstObjects[3] - Dep: Marketing Comp:DEF Progress: 3
In, lstObjects[1] - Dep: Sales Comp:ABC Progress: 2
lstObjects[4] - Dep: Sales Comp:ABC Progress: 1
In this I should get lstObjects[3] - Dep: Sales Comp:ABC Progress: 2
Finally my list should be:
1)Dep: Marketing Comp:ABC Progress: 2
2)Dep: Marketing Comp:DEF Progress: 3
3)Dep: Sales Comp:ABC Progress: 2
提前致谢。
答案 0 :(得分:5)
您可以在GroupBy
和Dep
上使用Comp
。
var result = lstObjects
.GroupBy(x=> new {x.Dep, x.Comp})
.Select(x=> new
{
Department = x.Key.Dep,
Comp = x.Key.Comp ,
Progress = x.Max(x => m.Progress)
});
答案 1 :(得分:3)
GroupBy 2属性应该起作用:
List<SomeObjects> uniqueWithMax = (from rec in lstObjects
group rec by new { rec.Dep, rec.Comp } into grp
select new SomeObjects
{
Dep = grp.Key.Dep,
Comp = grp.Key.Comp,
Progress = grp.Max(x => x.Progress)
}).ToList();
答案 2 :(得分:2)
首先按Dept
和Comp
进行分组。然后,对于每个组,使用具有最高Progress
的元素。后者可以用几种方式实现,我最喜欢LINQ to Objects(缺少标准MaxBy
)在线性时间内使用Aggregate
方法:
var result =
(from e in lstObjects
group e by new { e.Dep, e.Comp } into g
select g.Aggregate((a, b) => b.Progress > a.Progress ? b : a))
.ToList();
答案 3 :(得分:0)
var DepCompHighestProgress =
from d in lstObjects
group d by new { d.Dep, d.Comp } into oGrouped
select new
{
Dep = oGrouped.Key.Dep,
Comp = oGrouped.Key.Comp,
Progress = oGrouped.Max(depcomp => depcomp.Progress)
};