Linq OrderBy特定值未在分组内排序

时间:2015-02-16 21:22:58

标签: c# linq

所以标题可能毫无意义......

我有一个产品清单

"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中实现这一点????

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

尝试以下方法:

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

中间的.ThenBy(c => c)应该按字母顺序排序。

相关问题