3

如何使用 linq 根据一个人的钱对以下列表进行计数、分组和排序?

        Person[] names = { new Person{ Name = "Harris", Money = 100 }, 
                                new Person{ Name = "David", Money = 100 },
                                new Person{Name = "Harris", Money = 150},
                                new Person{Name = "Mike", Money = 100},
                                new Person{Name = "Mike", Money = 30},
                                new Person{Name = "Mike", Money = 20} };

结果将返回:

Harris 250 
Mike 150 
David 100
4

2 回答 2

8
 var personMoney = names.GroupBy(x=>x.Name)
                   .Select(x=>new {Name = x.Key, AllMoney = x.Sum(y=>y.Money)})
                   .OrderByDescending(x=>x.AllMoney).ToList();
于 2012-05-06T20:09:45.023 回答
7
from p in names
group p by p.Name into g
order by g.Key
select new { Name = g.Key, Amount = g.Sum(o => o.Amount) }
于 2012-05-06T19:25:10.713 回答