Home >Backend Development >C++ >How to Implement Dynamic LINQ Ordering for `IEnumerable` and `IEnumerable`?

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

Susan Sarandon
Susan SarandonOriginal
2025-02-02 22:36:12111browse

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

/ The dynamic linq sort IEnumerable<T> IQueryable<T>

Expansion method

IEnumerable<T> Although the dynamic Linq provides convenient syntax for sorting, similar functions are not directly applicable to

. To solve this problem, you can use the following extension methods to add

, IQueryable<T>, IEnumerable<T> and IEnumerable<T> Function: OrderBy OrderByDescending ThenBy Use ThenByDescending

together with
<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>

To use these extensions with , you can use the IEnumerable<T> expansion method to convert it to :

IEnumerable<T> Use AsQueryable Dynamic sorting IQueryable

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

var orderedItems = queryableItems.OrderBy("Property");</code>
In addition to the basic sorting method, you can also use

dynamic sorting to further expand the function. This is an example:

The above is the detailed content of How to Implement Dynamic LINQ Ordering for `IEnumerable` and `IEnumerable`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn