如果我有以下集合:
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
var query = from p in foos
group p by p.Name into g
select new
{
Name = g.Key,
Value = g.Max(a => a.Value)
};
var filteredFoos =
foos.GroupBy(x => x.Name)
.Select(x => new { Name = x.Key, Value = x.Max(f => f.Value) });
试试这个查询:
var filteredFoos = foos.GroupBy(x => x.Name)
.Select(p => new { p.Key, p.Max(x => x.Value) });
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是一个原语