首页 > 后端开发 > C++ > 动态的LINQ订购可以应用于' IEnumerable”以及`iqueryable'?

动态的LINQ订购可以应用于' IEnumerable”以及`iqueryable'?

Patricia Arquette
发布: 2025-02-02 22:41:10
原创
449 人浏览过

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

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板