2017-04-25 79 views
1

我有以下查詢加入StationId加入的火車站對象和ExpenditureData對象的集合,我想獲得前10站StationCargoCodes(Station對象屬性),並選擇前10的ExpenditureCost的總和,但我不能得到正確的語法:LINQ查詢到組並獲得總和

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做這個分組和總和?

+1

它不應該是'.SUM(E => e.expenditureAmount)'? –

+2

總和是一個減少。它將返回一個金額並終止查詢。你可以將查詢的公共部分封裝爲一個方法,然後分別調用.Sum和(GroupBy-> Take) – Novaterata

+0

是的,已經更新了:)但是我認爲語法不正確。 – Theomax

回答

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

@Novaterata我不這麼認爲。我認爲OP希望獲得前10名的「StationCargoCode」以及他們的總和。獲得前10名'StationCargoCode'將不會很有用,因爲它們只是代碼。也許我錯了,所以我們會看看OP說什麼。 – CodingYoshi

+0

基本上我需要的輸出是:StationCargoCode | 599,StationCargoCode | 580,StationCargoCode | 520等......按照最高的支出量排在前10名的最低排名。 – Theomax

+0

@Theomax是的,這就是我的回答所做的。那麼問題是什麼? – CodingYoshi

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 
+0

是否可以修改此查詢以選擇前10個電臺的支出金額的總和? – Theomax

+0

是不是這是做什麼?對不起,我沒有注意到order by e.expenditureAmount遞減,你不應該需要反向 –