LINQ making orderbydesc generic



我已经编写了LINQ查询如下,但只是想知道我是否可以使其更通用,并摆脱硬编码值。

switch (sortOrder)
{
    case "DESC":
        if(sortBy == "A")
            query = query.OrderByDescending(x => x.Field1);
        if(sortBy == "B")
            query = query.OrderByDescending(x => x.Field2);
        if (sortBy == "C")
            query = query.OrderByDescending(x => x.Field3);
        break;
    default:
        if(sortBy == "A")
            query = query.OrderBy(x => x.Field1);
        if(sortBy == "B")
            query = query.OrderBy(x => x.Field2);
        if (sortBy == "C")
            query = query.OrderBy(x => x.Field3);
        break;
}

提到的链接重复不是我正在寻找的答案。在这个问题中,用户通过先排序ASC然后排序Desc来提问。

在我的情况下,我必须排序ASC或DESC。

你只能使用Reflection i guess:

static IEnumerable<T> Order<T, V>(IEnumerable<T> query, string sortOrder, 
                                    Func<T, V> fieldSelector)
{
    string methodName = sortOrder == "DESC" ? "OrderByDescending" : "OrderBy";
    MethodInfo method = typeof(Enumerable).GetMethods()
                                          .Where(x => x.Name.Contains(methodName))
                                          .FirstOrDefault();
    MethodInfo genericMethod = method.MakeGenericMethod(typeof(Resource), typeof(V));
    var orderedResults = (IEnumerable<T>)genericMethod.Invoke(null, 
                                    new object[] { query, fieldSelector });
    return orderedResults;
}

用法:

var orderdResults = Order(query, "DESC", x => x.CategoryId).ToList();

我不明白你为什么要重新实现LINQ的OrderBy(),但这是最明智的方法,我想:

public static class Extensions
{
    public static IOrderedQueryable<TSource> Order<TSource, TKey>(
        this IQueryable<TSource> source, 
        Expression<Func<TSource, TKey>> keySelector, 
        bool descending = false)
    {
        return descending 
            ? source.OrderByDescending(keySelector)
            : source.OrderBy(keySelector);
    }   
}

您将像标准OrderBy()一样使用它,即您给它一个选择TSource属性的表达式:

var newest = query.Order(x => x.Id, true).First();
var oldest = query.Order(x => x.Id).First();

工作示例:https://dotnetfiddle.net/TcEEqY

相关内容

  • 没有找到相关文章

最新更新