首頁 > 後端開發 > C++ > 動態的LINQ訂購可以應用於' IEnumerable”以及`iqueryable'?

動態的LINQ訂購可以應用於' IEnumerable”以及`iqueryable'?

Patricia Arquette
發布: 2025-02-02 22:41:10
原創
389 人瀏覽過

Can Dynamic LINQ Ordering Be Applied to `IEnumerable` as Well as `IQueryable`?

dynamic linq Orderby在iEnumerable上< t> / iqueryable< t>

在動態linq中,您可以使用類似SQL的字符串(例如,“ orderby(“ name,age desc”)”)來訂購結果。但是,到目前為止可用的示例僅適用於iQueryable< t>。這就提出了一個問題:是否可以將此功能擴展到IEnumerable< t>?利用令人不快的方法。但是,下面的代碼作為所需的核心表達邏輯:

>在動態linq to-objects方案中合併動態功能

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)
{
    string[] props = property.Split('.');
    Type type = typeof(T);
    ParameterExpression arg = Expression.Parameter(type, "x");
    Expression expr = arg;
    foreach (string prop in props)
    {
        // use reflection to mirror LINQ
        PropertyInfo pi = type.GetProperty(prop);
        expr = Expression.Property(expr, pi);
        type = pi.PropertyType;
    }
    Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
    LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);

    object result = typeof(Queryable).GetMethods().Single(
            method => method.Name == methodName
                    && method.IsGenericMethodDefinition
                    && method.GetGenericArguments().Length == 2
                    && method.GetParameters().Length == 2)
            .MakeGenericMethod(typeof(T), type)
            .Invoke(null, new object[] { source, lambda });
    return (IOrderedQueryable<T>)result;
}
登入後複製
> 。

以上是動態的LINQ訂購可以應用於' IEnumerable”以及`iqueryable'?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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