2009-04-16 87 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); 

希望这将解决您的问题,比前一个更容易;)

干杯