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

本文关键字:else LINQ 代码 if 何清理 我的 | 更新日期: 2023-09-27 18:19:41

我有这样的东西:

        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查询。有什么建议吗?

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

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

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);
}

现场演示


如果你想把它作为所有列表的通用解决方案,你可以把它创建为一个扩展方法

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);