代码之家  ›  专栏  ›  技术社区  ›  SharpAffair

将OrderByDescending添加到Linq语句

  •  0
  • SharpAffair  · 技术社区  · 15 年前

    我有以下代码可以从字符串中提取关键字:

    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) 结果不正确。如何使它正确?

    3 回复  |  直到 13 年前
        1
  •  4
  •   Anthony Pegram    15 年前

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

    .Select(...whatever...).OrderByDescending(item => item.count);
    
        2
  •  2
  •   Ruben    15 年前

    您之所以产生误解,是因为您在lambda中为变量指定了与匿名类型上的属性相同的名称。这个 OrderByDescending(count => count) OrderByDescending(x => x.count) .

        3
  •  2
  •   Community Mohan Dere    9 年前

    在GroupBy和call之后使用它 g.Count() Select 声明:

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

    编辑:实际上我更喜欢 Anthony's answer Count() 两次执行,而Anthony的方法是根据已经计算的 计数() 选择 陈述。只是在构建干净的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 };
    
    推荐文章