【问题标题】:Linq OrderBy specific values not ordering within groupingsLinq OrderBy 特定值不在分组内排序
【发布时间】:2015-02-19 06:22:47
【问题描述】:

所以标题可能没有意义......

我有一个产品列表

"Ind Apples", "Ind Bananas", "Ind Carrots", "Ind Dates", "Ind Eggplants", "Bulk Apples", "Bulk Bananas", "Bulk Carrots", "Bulk Dates", "Potatoes", "Oranges", "Melons"

我的 linq 查询如下:

  var query = db.products
    .OrderBy(c => c.ProductName.StartsWith("Ind"))
    .ThenBy(c => c.ProductName.StartsWith("Bulk"));

我希望我的列表首先显示所有以“Ind”开头的项目,然后是以“Bulk”开头的项目,然后是其他所有项目......

我的列表中的内容如下:

"Ind Bananas"
"Ind Eggplants"
"Ind Carrots"
"Ind Apples"
"Bulk Apples"
"Bulk Dates"
"Bulk Carrots"
"Bulk Bananas"
"Oranges"
"Melons"
"Potatoes"

所以它是按我的规范排序的......但在每个分组“Ind”,“Bulk”中它不是......有没有办法(除了浏览列表并手动指定我想要每个项目的位置) 在 linq 中实现这一点????

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    我会在外部分组中链接条件运算符,然后按字符串分组:

    var query = db.products
                  .OrderBy(c => c.ProductName.StartsWith("Ind") ? 0 : 
                                c.ProductName.StartsWith("Bulk") ? 1 : 2)
                  .ThenBy(c => c.ProductName);
    

    var query = db.products
                  .OrderBy(c => c.ProductName.StartsWith("Ind") ? 0 : 1)
                  .ThenBy(c => c.ProductName.StartsWith("Bulk") ? 0 : 1)
                  .ThenBy(c => c.ProductName);
    

    【讨论】:

      【解决方案2】:

      尝试以下方法:

       OrderByDescending(c => c.FruitType.StartsWith("Ind")).ThenBy(c => c).ThenBy(c => c.FruitType.StartsWith("Bulk"));
      

      中间的 .ThenBy(c =>c) 应该强制执行字母排序。

      【讨论】:

      • 我很抱歉将我的答案作为问题提出。我会注意的。
      • 是的。我还在最后指定了 .ThenBy(c=>c.ProductName) ,但这没有用。
      • 这就像我需要在每个已经存在的 orderbys 里面做一个 orderby,但你不能......
      • 我只是用一点不同的 LINQ 查询试了一下,它的排序正确。我编辑了我的答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-26
      • 2020-05-30
      • 2011-03-01
      • 1970-01-01
      相关资源
      最近更新 更多