How Order by Case in LINQ

故事扮演 提交于 2021-02-05 08:41:29

问题


I have this answer Entity framework OrderBy "CASE WHEN" but this only handle two options

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

I have a text field and want rows appear on an specific order. In sql I would do:

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:


How about creating a map of your sort order?

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


来源:https://stackoverflow.com/questions/50225333/how-order-by-case-in-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!