使用字符串表達式動態排序 IEnumerable
原始問題:
在搜索動態 LINQ 示例時,發現了一種方法可以使用類似 SQL 的字符串(例如,“OrderBy("Name, Age DESC")”)對 IQueryable
答案:
為了在不使用 Dynamic LINQ 庫的情況下實現這一點,以下代碼片段提供了核心表達式邏輯:
<code class="language-C#">public static IOrderedQueryable<T> OrderBy<T>( this IQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "OrderBy"); } // ...省略其余代码以简洁起见...</code>
此代碼允許通過將 IEnumerable
動態 LINQ 集成的擴展:
將此功能擴展到動態 LINQ:
<code class="language-C#">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); } // ...省略其余代码以简洁起见...</code>
此代碼在 LINQ to Objects 中提供了動態排序功能。
以上是如何使用字符串表達式動態訂購iEnumerable且可音錄?的詳細內容。更多資訊請關注PHP中文網其他相關文章!