2

如果我有以下收藏:

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

4 回答 4

5
var filteredFoos = 
    foos.GroupBy(x => x.Name)
        .Select(x => new { Name = x.Key, Value = x.Max(f => f.Value) });
于 2013-01-07T16:51:01.063 回答
5
var query = from p in foos
            group p by p.Name into g
            select new
            {
                Name = g.Key,
                Value = g.Max(a => a.Value)
            };
于 2013-01-07T16:51:19.860 回答
2

试试这个查询:

var filteredFoos = foos.GroupBy(x => x.Name)
                       .Select(p => new { p.Key, p.Max(x => x.Value) });
于 2013-01-07T16:50:12.713 回答
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 是一个原语。

于 2013-01-08T19:18:51.537 回答