首頁 > 後端開發 > C++ > 如何使用字符串表達式動態訂購iEnumerable且可音錄?

如何使用字符串表達式動態訂購iEnumerable且可音錄?

Susan Sarandon
發布: 2025-02-02 22:31:10
原創
891 人瀏覽過

How Can I Dynamically Order IEnumerable and IQueryable Using String Expressions?

使用字符串表達式動態排序 IEnumerable / IQueryable

原始問題:

在搜索動態 LINQ 示例時,發現了一種方法可以使用類似 SQL 的字符串(例如,“OrderBy("Name, Age DESC")”)對 IQueryable 實例進行排序。有沒有辦法將此功能擴展到 IEnumerable

答案:

為了在不使用 Dynamic LINQ 庫的情況下實現這一點,以下代碼片段提供了核心表達式邏輯:

public static IOrderedQueryable<T> OrderBy<T>(
    this IQueryable<T> source,
    string property)
{
    return ApplyOrder<T>(source, property, "OrderBy");
}

// ...省略其余代码以简洁起见...
登入後複製

此代碼允許通過將 IEnumerable 包裝在 AsQueryable() 中來對其進行排序。

動態 LINQ 集成的擴展:

將此功能擴展到動態 LINQ:

using Microsoft.CSharp.RuntimeBinder;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Runtime.CompilerServices;

// ...省略其余代码以简洁起见...

public static IOrderedEnumerable<dynamic> OrderBy(
    this IEnumerable<dynamic> source,
    string property)
{
    return Enumerable.OrderBy<dynamic>(
        source,
        AccessorCache.GetAccessor(property),
        Comparer<object>.Default);
}

// ...省略其余代码以简洁起见...
登入後複製

此代碼在 LINQ to Objects 中提供了動態排序功能。

以上是如何使用字符串表達式動態訂購iEnumerable且可音錄?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板