6

我正在检查排序参数并构建一堆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();
}

我怎样才能使它变得更好?

4

3 回答 3

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();
于 2012-05-11T19:50:04.950 回答
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();
于 2012-05-11T19:50:35.323 回答
1

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

IEnumerable<T> 上的动态 LINQ OrderBy

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

于 2012-05-11T19:52:34.920 回答