如何使用LINQ从列表中选择更大的分组值

时间:2018-10-03 07:32:22

标签: c# linq group-by

我有对象列表(名称是列表),例如下一个值:

[0] {Id='04239',Color='03',MatPre='145698',Stz=210,Spp=1}
[1] {Id='04239',Color='03',MatPre='145698',Stz=210,Spp=3}
[2] {Id='04239',Color='KB',MatPre='145698',Stz=210,Spp=3}
[3] {Id='04239',Color='KB',MatPre='145698',Stz=210,Spp=2}
[4] {Id='04239',Color='03',MatPre='145698',Stz=210,Spp=4}

我想得到的结果或新列表是带有v项的列表:

[0] {Id='04239',Color='03',MatPre='145698',Stz=210,Spp=3}
[1] {Id='04239',Color='03',MatPre='145698',Stz=210,Spp=4}
[2] {Id='04239',Color='KB',MatPre='145698',Stz=210,Spp=3}

我需要这样的东西

var test = list.GroupBy(x => new { x.Color })
               .Where(x => x.Spp is greater than first 
                                 smaller x.Spp in same 
                                 group of Color)
               .SelectMany(x => x).ToList();

我不知道该怎么做。

1 个答案:

答案 0 :(得分:3)

这应该做到这一点,尽管每次调用Min可能并不高效,但是您可以考虑使用查询语法来使其更好:

list.GroupBy(x => x.Color)
    .SelectMany(g => g.Where(x => x.Spp > g.Min(_ => _.Spp));