Order list by special enum value in linq

A simpler approach is to just evaluate the enum and return comparison value:

 var result = list.OrderBy(item => item.myEnum == myEnum.foo ? 1 : 2)
                  .ThenBy(item => item.myEnum == myEnum.boo ? 1 : 2)
                  .ThenBy(item => item.myEnum == myEnum.goo ? 1 : 2); 

This way you won't need extra variables and a more readable code.

Sample: https://repl.it/repls/CornsilkGiganticDevelopers


For arbitrary enum and sort order e.g.

  public enum MyEnum {
    boo = -1,
    foo = 3, 
    goo = 154,    
  };

I suggest mapping:

  // we want foo, boo, goo order
  internal static readonly Dictionary<MyEnum, int> enumOrder = 
    new  Dictionary<MyEnum, int>() {
      {MyEnum.foo, 1},
      {MyEnum.boo, 2},
      {MyEnum.goo, 3},
  };

Query:

  var result = source
    .OrderBy(item => enumOrder[item.SecondField]) // map second field on the desired order
    .ThenBy(item => item.FirstField);      

The below code will sort yourData by two properties - NameOfYourEnumPropertyHere and NameOfYourIntPropertyHere. You need to replace with your property names and away you go.

var sortedResult = yourData
    .OrderBy(z => z.NameOfYourEnumPropertyHere)
    .ThenBy(z => z.NameOfYourIntPropertyHere).ToList();

Tags:

C#

Linq

Enums