簡體   English   中英

動態 Linq - 如何按 Enum 屬性按字母順序對集合進行排序?

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

我有一個實體集合。

屬性之一是枚舉。

如何按其枚舉名稱而不是值的字母順序對集合進行排序?

在 LINQ 中,它看起來像這樣:

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

我似乎無法將其翻譯為動態 Linq。

我試圖直接把它,但它拋出一個異常:

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

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. 源代碼中可用類型的完整列表

有關 dotnet 核心答案,請參閱https://dynamic-linq.net/advanced-configuration上的文檔。 您需要創建一個自定義類型提供程序,而不是創建一個解析器配置並在您的查詢中使用它。

下面的例子。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM