LINQ查询到Group并得到Sum

时间:2017-04-25 22:13:09

标签: c# linq

我有以下查询,它连接了一个由StationId加入的RailwayStation对象和ExpenditureData对象的集合,我试图获得前10个StationCargoCodes(Station对象上的属性),并选择ExpenditureCost的总和为顶部10但我无法得到正确的语法:

var data = (from s in stations join e in expenditureData on s.stationId 
equals e.StationId 
orderby e.expenditureAmount descending 
select s)
.Sum(e => e.expenditureAmount)
.GroupBy(n => n.StationCargoCode)
.Take(10);

我需要做什么LINQ才能进行分组并对此进行求和?

2 个答案:

答案 0 :(得分:2)

var query = from s in stations
            join e in expenditureData
                on s.stationId equals e.StationId into se
            group se by new
            {
                s.StationCargoCode, ExpenditureCostSum = se.Sum(x => x.ExpenditureCost)
            } into g
            orderby g.Key.ExpenditureCostSum descending
            select g.Key;

var top10 = query.Take(10).ToList();

答案 1 :(得分:1)

你的好处是我的朋友错了。 考虑一下,你获得前10名,然后进行总和操作。 上面的代码得到所有的总和,然后你采取最后10。 您的代码应该更像是

var data = (from s in stations 
join e in expenditureData on s.stationId equals e.StationId 
orderby e.expenditureAmount descending 
select s)
.GroupBy(n => n.StationCargoCode) // you may need to do Select(x=> x.First()) if you want to have only distinct
.Take(10) // take the top 10 eg from 0 to 10
.Sum(e => e.expenditureAmount) // then Do sum on the result which will be the top 10