首頁 >後端開發 >C++ >如何實現' IEnumerable”和`ienumerable'的動態LINQ訂購?

如何實現' IEnumerable”和`ienumerable'的動態LINQ訂購?

Susan Sarandon
Susan Sarandon原創
2025-02-02 22:36:12167瀏覽

How to Implement Dynamic LINQ Ordering for `IEnumerable` and `IEnumerable`?

IEnumerable<T> / IQueryable<T> 的動態LINQ排序

IEnumerable<T> 的擴展方法

雖然動態LINQ為IQueryable<T>排序提供了便捷的語法,但類似的功能並不直接適用於IEnumerable<T>。為了解決這個問題,您可以使用以下擴展方法,為IEnumerable<T>添加OrderByOrderByDescendingThenByThenByDescending功能:

<code class="language-csharp">public static IOrderedQueryable<T> OrderBy<T>(
    this IQueryable<T> source,
    string property)
{
    return ApplyOrder<T>(source, property, "OrderBy");
}

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

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

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

static IOrderedQueryable<T> ApplyOrder<T>(
    IQueryable<T> source,
    string property,
    string methodName)
{
    // 为简洁起见,省略实现
}</code>

IEnumerable<T>一起使用

要將這些擴展方法與IEnumerable<T>一起使用,您可以使用AsQueryable擴展方法將其轉換為IQueryable

<code class="language-csharp">IEnumerable<T> items = ...;
IQueryable<T> queryableItems = items.AsQueryable();

var orderedItems = queryableItems.OrderBy("Property");</code>

使用IEnumerable<dynamic>進行動態排序

除了基本的排序方法外,您還可以使用IEnumerable<dynamic>上的動態排序來進一步擴展功能。這是一個示例:

<code class="language-csharp">using System.Dynamic;

public static IOrderedEnumerable<dynamic> OrderBy(
    this IEnumerable<dynamic> source,
    string property)
{
    // 为简洁起见,省略实现
}

// 其他排序方法 (OrderByDescending, ThenBy, ThenByDescending)

IEnumerable<dynamic> data = ...;

var orderedData = data.OrderBy("Property");</code>

以上是如何實現' IEnumerable”和`ienumerable'的動態LINQ訂購?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn