2012-05-06 162 views
3

如何使用linq來計算,分組和排序基於個人錢的以下列表?C#linq group by

 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 

回答

8
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) } 
+1

挑剔:有序 - 通過由樣品輸出矛盾。 –

+2

也可以寫樣本數據:Amount = g.Sum(o => o.Money) –

10
var personMoney = names.GroupBy(x=>x.Name) 
        .Select(x=>new {Name = x.Key, AllMoney = x.Sum(y=>y.Money)}) 
        .OrderByDescending(x=>x.AllMoney).ToList();