如何改进此排序代码?

时间:2012-05-11 19:45:56

标签: c# .net linq

我正在检查sort参数并构建一堆if语句:

if (sortDirection == "ASC")
{
    if (sortBy == "Id")
        return customerList.OrderBy(x => x.Id).Skip(startIndex).Take(pageSize).ToList();
    if (sortBy == "FirstName")
        return customerList.OrderBy(x => x.FirstName).Skip(startIndex).Take(pageSize).ToList();
    if (sortBy == "City")
        return customerList.OrderBy(x => x.City).Skip(startIndex).Take(pageSize).ToList();
}
else
{
    if (sortBy == "Id")
        return customerList.OrderByDescending(x => x.Id).Skip(startIndex).Take(pageSize).ToList();
    if (sortBy == "FirstName")
        return customerList.OrderByDescending(x => x.FirstName).Skip(startIndex).Take(pageSize).ToList();
    if (sortBy == "City")
        return customerList.OrderByDescending(x => x.City).Skip(startIndex).Take(pageSize).ToList();
}

我如何做得更好?

3 个答案:

答案 0 :(得分:8)

将您的订单与查询的其余部分分开 - 您不必在代码库中复制的每个查询的相同部分(保留DRY):

var query = customerList;

if (sortDirection == "ASC")
{
    if (sortBy == "Id")
       query = query.OrderBy(x => x.Id);
    ///and so on
}

query = query.Skip(startIndex).Take(pageSize).ToList();

答案 1 :(得分:2)

使用反射:)

customerList = (sortDirection == "ASC")
   ? customerList
        .OrderBy(x => x.GetType().GetProperty(sortBy).GetValue(x, null))
        .Skip(startIndex)
        .Take(pageSize)
        .ToList()
   : customerList
        .OrderByDescending(x => x.GetType().GetProperty(sortBy).GetValue(x, null))
        .Skip(startIndex)
        .Take(pageSize)
        .ToList();

答案 2 :(得分:1)

看起来您只想按属性名称作为字符串进行排序。在这种情况下,实际上已经通过使用“Dynamic LINQ”解决了这个问题:

Dynamic LINQ OrderBy on IEnumerable<T>

看看这个问题的答案,它应该为您提供解决问题的示例代码。