c# - 为通用列表创建排序函数

标签 c# generics

我有一个按对象字段对通用列表进行排序的方法:

public static IQueryable<T> SortTable<T>(IQueryable<T> q, string sortfield, bool ascending)
{
    var p = Expression.Parameter(typeof(T), "p");

    if (typeof(T).GetProperty(sortfield).PropertyType == typeof(int?))
    {
        var x = Expression.Lambda<Func<T, int?>>(Expression.Property(p, sortfield), p);
        if (ascending)
            q = q.OrderBy(x);
        else
            q = q.OrderByDescending(x);
    }
    else if (typeof(T).GetProperty(sortfield).PropertyType == typeof(int))
    {
        var x = Expression.Lambda<Func<T, int>>(Expression.Property(p, sortfield), p);
        if (ascending)
            q = q.OrderBy(x);
        else
            q = q.OrderByDescending(x);
    }
    else if (typeof(T).GetProperty(sortfield).PropertyType == typeof(DateTime))
    {
        var x = Expression.Lambda<Func<T, DateTime>>(Expression.Property(p, sortfield), p);
        if (ascending)
            q = q.OrderBy(x);
        else
            q = q.OrderByDescending(x);
    }
    // many more for every type
    return q;
}

有什么方法可以将这些 if 折叠成一个通用语句吗? 主要问题是对于这部分 Expression.Lambda<Func<T, int>> 我不确定如何通用地编写它。

最佳答案

如果您将 Queryable.OrderBy 扩展为其定义,则您不必使用 Expression.Lambda 的通用重载:

public static IQueryable<T> SortTable<T>(
    IQueryable<T> q, string sortfield, bool ascending)
{
    var p = Expression.Parameter(typeof(T), "p");
    var x = Expression.Lambda(Expression.Property(p, sortfield), p);

    return q.Provider.CreateQuery<T>(
               Expression.Call(typeof(Queryable),
                               ascending ? "OrderBy" : "OrderByDescending",
                               new Type[] { q.ElementType, x.Body.Type },
                               q.Expression,
                               x));
}

关于c# - 为通用列表创建排序函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2646703/

相关文章:

c# - 获得发光效果的最佳方式 Windows Phone 7

c# - 如何在 Xamarin Shell 中自定义顶部选项卡 (ShellSection) 的外观?

C# DataTable vs 一些通用的集合性能

c# - 如何在 C# 的通用抽象类中定义类型 T 必须具有字段 “ID”

c# - OpenPop : how can I turn off DEBUG printing?

c# - 使用内联查询进行单元测试 Dapper

c# - Lucene .NET 搜索结果

java - Spring jdbcTemplate : generic code to run a select query with model name provided

java - 泛型的返回类型,何时使用 <T>returnType<T> 以及何时仅使用 returnType<T>?

Java 通用问题