Dynamic Linq - how do you sort a collection by Enum property alphabetically?

406 Views Asked by At

I have a collection of entities.

One of the properties is an enumeration.

How can I sort the collection alphabetically by its enum name instead of value?

In LINQ it would look like this:

var a = collection.OrderBy(x => Enum.GetName(x.OrderType.GetType(), x.OrderType)).ToList();

I can't seem to translate this to Dynamic Linq.

I tried to put it directly, but it throws an Exception:

collection.OrderBy("x => Enum.GetName(x.OrderType.GetType(), x.OrderType) ascending")
1

There are 1 best solutions below

0
BurnsBA On

For .net framework (not core), see this answer: Call function in dynamic linq which explains that only certain types are available in dynamic linq expressions. Full list of types available in source code

For the dotnet core answer, see the documentation at https://dynamic-linq.net/advanced-configuration . You need to create a custom type provider, than create a parser configuration and use that in your query.

Example below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Dynamic.Core.CustomTypeProviders;
                    
public class Program
{   
    public class MyCustomTypeProvider : DefaultDynamicLinqCustomTypeProvider
    {
        public override HashSet<Type> GetCustomTypes() =>
            new[] { typeof(System.Enum), typeof(System.ConsoleColor) }.ToHashSet();
    }
    
    public static void Main()
    {
        // example data source (using primitive data type)
        var listy = new List<System.ConsoleColor>();
        listy.Add(ConsoleColor.DarkBlue);
        listy.Add(ConsoleColor.Yellow);
        listy.Add(ConsoleColor.Cyan);
        listy.Add(ConsoleColor.White);

        // regular linq query
        Console.WriteLine(String.Join(", ", listy.OrderBy(x => Enum.GetName(x.GetType(), x))));
        
        var config = new ParsingConfig
        {
            CustomTypeProvider = new MyCustomTypeProvider()
        };
        
        // dynamic linq calling Enum method
        Console.WriteLine(String.Join(", ", listy.AsQueryable().OrderBy(config, "x => Enum.GetName(x.GetType(), x)")));
    }
}

output

Cyan, DarkBlue, White, Yellow
Cyan, DarkBlue, White, Yellow