如何在LINQ中按案例排序

时间:2018-05-08 03:23:04

标签: c# linq sql-order-by case

我有这个答案Entity framework OrderBy "CASE WHEN",但这只能处理两个选项

var p = ctx.People.OrderBy(p => (p.IsQualityNetwork == 1 || p.IsEmployee == 1) ? 0 : 1)
                  .ThenBy(p => p.Name);

我有一个文本字段,希望在特定订单上显示行。在sql我会做:

ORDER BY CASE when name = "ca" then 1
              when name = "po" then 2
              when name = "pe" then 3 
              when name = "ps" then 4
              when name = "st" then 5
              when name = "mu" then 6
         END

1 个答案:

答案 0 :(得分:5)

如何创建排序顺序的地图?

var sortOrder = new Dictionary<string,int>
{
  { "ca", 1 },
  { "po", 2 },
  { "pe", 3 },
  { "ps", 4 },
  { "st", 5 },
  { "mu", 6 }
};

var defaultOrder = sortOrder.Max(x => x.Value) + 1;

var sortedPeople = ctx
  .People
  .AsEnumerable()
  .OrderBy(p => (p.IsQualityNetwork == 1 || p.IsEmployee == 1) ? 0 : 1)
  .ThenBy(p => sortOrder.TryGetValue(p.Name, out var order) ? order : defaultOrder);