首页 >后端开发 >C++ >如何在`ienumerable''和`iqueryable''上执行动态linq订购?

如何在`ienumerable''和`iqueryable''上执行动态linq订购?

Barbara Streisand
Barbara Streisand原创
2025-02-02 22:46:21883浏览

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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn