简体   繁体   English

将OrderByDescending添加到Linq语句

[英]Add OrderByDescending to Linq statement

I've got the following code to extract keywords from a string: 我有以下代码从字符串中提取关键字:

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
                 });

Now I need to add OrderByDescending to it, but not sure where to place it. 现在,我需要向其中添加OrderByDescending ,但不确定将其放置在何处。 .GroupBy(str => str).OrderByDescending(count => count) yielded incorrect results. .GroupBy(str => str).OrderByDescending(count => count)产生不正确的结果。 How to make it right? 如何使它正确?

您可以在选择之后添加它。

.Select(...whatever...).OrderByDescending(item => item.count);

Use it after the GroupBy and call g.Count() the same way you did in your Select statement: 在GroupBy之后使用它,并以与Select语句相同的方式调用g.Count()

.GroupBy(str => str)
.OrderByDescending(g => g.Count())
.Select(g => new ...) // rest of your code here

EDIT: I actually prefer Anthony's answer to my own and was about to modify mine but by then he had posted his response. 编辑:我实际上更喜欢安东尼的回答 ,并且打算修改我的回答 ,但那时他已经发表了自己的回答。 It's a very minor concern and is a premature optimization, but my posted approach will be slightly slower when dealing with large collections since Count() is being executed twice, whereas Anthony's approach is sorting on the already computed Count() made in the Select statement. 这是一个很小的问题,是一个过早的优化,但是在处理大型集合时,由于Count()被执行了两次,所以我发布的方法会稍慢一些,而Anthony的方法是对Select语句中已经计算出的Count()进行排序。 Just something to keep in mind when constructing clean LINQ queries. 构造干净的LINQ查询时要记住的一点。

As an aside, in query syntax we can get around this by storing the count in a let (sure, this is possible in fluent syntax but feels more natural in query syntax) which would provide good performance. 顺便说一句,在查询语法中,我们可以通过将计数存储在let来解决这个问题(当然,这在流畅的语法中是可能的,但在查询语法中感觉更自然),它将提供良好的性能。 Something like this: 像这样:

var query = from g in text.Split(...).GroupBy(str => str)
            let count = g.Count()
            orderby count descending
            select new { str = g.Key, Count = count };

You're misunderstanding is due to the fact that you give the variable in the lambda the same name as a property on the anonymous type. 您误会是因为您给lambda中的变量赋予了与匿名类型属性相同的名称。 The OrderByDescending(count => count) sorts on the whole object. OrderByDescending(count => count)对整个对象进行排序。 What you want is to sort on the count-property, so you should use OrderByDescending(x => x.count) . 您想要的是对计数属性进行排序,因此您应该使用OrderByDescending(x => x.count)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM