2009-04-16 126 views
39

我有以下linq查詢,它工作正常。我不知道我是如何訂購該組的結果。如何在Linq中訂購組結果?

from a in Audits 
join u in Users on a.UserId equals u.UserId 
group a by a.UserId into g 
select new { UserId = g.Key, Score = g.Sum(x => x.Score) } 

結果目前按UserId升序排列。我在分數下降後。

謝謝:)

回答

64

只需添加排序依據條款;-)

from a in Audits 
join u in Users on a.UserId equals u.UserId 
group a by a.UserId into g 
let score = g.Sum(x => x.Score) 
orderby score descending 
select new { UserId = g.Key, Score = score }; 
+0

我嘗試添加一個orderby,但它沒有工作。但是你做的是在那裏添加一個LET語句!嗯..這很有趣... – 2009-04-16 11:57:03

+0

我沒有檢查,但我認爲LET是不必要的,但是。只是「order by g.Sum(x => x.Score)」就夠了嗎? – 2009-04-16 12:54:38

13
var results = 
(from a in Audits 
join u in Users on a.UserId equals u.UserId 
group a by a.UserId into g 
select new { UserId = g.Key, Score = g.Sum(x => x.Score) }) 
.OrderByDescending(p=>p.Score); 

希望這將解決您的問題,比前一個更容易;)

乾杯