[英]Add OrderByDescending to Linq statement
我有以下代码从字符串中提取关键字:
var results = text.Split(new char[]{' ',',','.','!','?','_',':',';','/','(',')','\n','\r','-','*','"','/','\\','$','%','+','-','='}) // default split by whitespace
.GroupBy(str => str) // group words by the value
.Select(g => new
{
str = g.Key, // the value
count = g.Count() // the count of that value
});
现在,我需要向其中添加OrderByDescending
,但不确定将其放置在何处。 .GroupBy(str => str).OrderByDescending(count => count)
产生不正确的结果。 如何使它正确?
您可以在选择之后添加它。
.Select(...whatever...).OrderByDescending(item => item.count);
在GroupBy之后使用它,并以与Select
语句相同的方式调用g.Count()
:
.GroupBy(str => str)
.OrderByDescending(g => g.Count())
.Select(g => new ...) // rest of your code here
编辑:我实际上更喜欢安东尼的回答 ,并且打算修改我的回答 ,但那时他已经发表了自己的回答。 这是一个很小的问题,是一个过早的优化,但是在处理大型集合时,由于Count()
被执行了两次,所以我发布的方法会稍慢一些,而Anthony的方法是对Select
语句中已经计算出的Count()
进行排序。 构造干净的LINQ查询时要记住的一点。
顺便说一句,在查询语法中,我们可以通过将计数存储在let
来解决这个问题(当然,这在流畅的语法中是可能的,但在查询语法中感觉更自然),它将提供良好的性能。 像这样:
var query = from g in text.Split(...).GroupBy(str => str)
let count = g.Count()
orderby count descending
select new { str = g.Key, Count = count };
您误会是因为您给lambda中的变量赋予了与匿名类型属性相同的名称。 OrderByDescending(count => count)
对整个对象进行排序。 您想要的是对计数属性进行排序,因此您应该使用OrderByDescending(x => x.count)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.