LINQ GroupBy和Select在不同的属性上

时间:2013-01-07 16:47:58

标签: c# .net linq group-by linq-to-objects

如果我有以下收藏品:

var foos = new List<Foo>
{
    new Foo{ Name = "A", Value = 1 },
    new Foo{ Name = "B", Value = 1 },
    new Foo{ Name = "B", Value = 2 },
    new Foo{ Name = "C", Value = 1 },
};

我想最终:

A-1
B-2
C-1

如果是重复的“B”,我想选择价值最高的“B”?

类似的东西:

var filteredFoos = foos.GroupBy(x => x.Name).Select_Duplicate_With_Highest_Value

4 个答案:

答案 0 :(得分:5)

var filteredFoos = 
    foos.GroupBy(x => x.Name)
        .Select(x => new { Name = x.Key, Value = x.Max(f => f.Value) });

答案 1 :(得分:4)

var query = from p in foos
            group p by p.Name into g
            select new
            {
                Name = g.Key,
                Value = g.Max(a => a.Value)
            };

答案 2 :(得分:2)

尝试此查询:

var filteredFoos = foos.GroupBy(x => x.Name)
                       .Select(p => new { p.Key, p.Max(x => x.Value) });

答案 3 :(得分:0)

对于排名超过2列的任何人:

var subquery = from p in foos
            group p by p.Name into g
            select new
            {
                Name = g.Key,
                Value = g.Max(a => a.Value)
            };
var query = from f in foos
            join s in subquery 
              on f.Name equals s.Name
            where f.Value == s.Value
            select f;

如果这是针对SQL的,请确保Name是基元。