如何清理我的if / else LINQ代码

时间:2014-08-28 14:22:42

标签: c# linq

我有这样的事情:

        if (sort == "Customer")
        {
            if (sortDirection == SortDirection.Descending)
                myList = myList.OrderByDescending(e => e.SiteOrganization.Organization.Name).ToList();
            else
                myList = myList.OrderBy(e => e.SiteOrganization.Organization.Name).ToList();
        }
        if (sort == "RequestType")
        {
            if (sortDirection == SortDirection.Descending)
                myList = myList.OrderByDescending(e => e.TypeId).ToList();
            else
                myList = myList.OrderBy(e => e.TypeId).ToList();
        }
        if (sort == "RequestedByShort")
        {
            if (sortDirection == SortDirection.Descending)
                myList = myList.OrderByDescending(e => e.RequestedByUser.ShortName).ToList();
            else
                myList = myList.OrderBy(e => e.RequestedByUser.ShortName).ToList();
        }

我想清理它,以便有类似

的东西
if (sortDirection == SortDirection.Descending)
                myList = myList.OrderByDescending(e => e.RequestedByUser.ShortName).ToList();
            else
                myList = myList.OrderBy(e => e.RequestedByUser.ShortName).ToList();

所以我只有一个LINQ查询,无论什么"排序"它是。有什么建议吗?

1 个答案:

答案 0 :(得分:4)

如果将排序逻辑移动到方法中,则可以直接传递谓词

public IList<TSource> SortBy<TSource, TMember>(IEnumerable<TSource> list, Func<TSource, TMember> selector, SortDirection direction)
{
    if (direction == SortDirection.Descending)
        return list.OrderByDescending(selector).ToList();
    else
        return list.OrderBy(selector).ToList();
}
...
if (sort == "Customer") {
    list = SortBy(list, x => x.SiteOrganization.Organization.Name, SortDirection.Descending);
} else if (sort == "RequestType") {
    list = SortBy(list, x => x.TypeId, SortDirection.Ascending);
} else if (sort == "RequestedByShort") {
    list = SortBy(list, x => x.RequestedByUser.ShortName, SortDirection.Descending);
}

Live demo


如果您想将其用作所有列表的通用解决方案,可以将其创建为扩展方法

public static class ListExt
{
    public static IList<TSource> SortBy<TSource, TMember>(this IEnumerable<TSource> list, Func<TSource, TMember> selector, SortDirection direction)
    {
        if (direction == SortDirection.Descending) {
            return list.OrderByDescending(selector).ToList();
        } else {
            return list.OrderBy(selector).ToList();
        }
    }
}
...
list = list.SortBy(x => x.TypeId, SortDirection.Ascending);