首頁 > 後端開發 > C++ > 如何在`ienumerable''和`iqueryable''上執行動態linq訂購?

如何在`ienumerable''和`iqueryable''上執行動態linq訂購?

Barbara Streisand
發布: 2025-02-02 22:46:21
原創
882 人瀏覽過

How Can I Perform Dynamic LINQ Ordering on Both `IEnumerable` and `IQueryable`?

>

dynamic linq Orderby in iEnumerable< t> / iQueryable< t> Dynamic Linq提供了一種使用類似SQL的字符串訂購數據的方便方法。但是,Visual Studio 2008示例中的示例僅適用於Iqueryable< t>。如果您想將此功能應用於iEnumerable< t>,則可以利用以下代碼:

>
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 (not ComponentModel) 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
                    &amp;&amp; method.IsGenericMethodDefinition
                    &amp;&amp; method.GetGenericArguments().Length == 2
                    &amp;&amp; method.GetParameters().Length == 2)
            .MakeGenericMethod(typeof(T), type)
            .Invoke(null, new object[] {source, lambda});
    return (IOrderedQueryable<T>)result;
}
登入後複製
>代碼:

以上是如何在`ienumerable''和`iqueryable''上執行動態linq訂購?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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