forby循环丢失范围中的orderby

时间:2018-08-10 11:08:05

标签: c# linq

在一些非常简单的事情上遇到麻烦(我希望)

我收到一个要排序的数组。我为键选择器创建了字典。 但是我错过了最后修复的问题,而不是ThenBy或每次都重新排序。

public List<Vehicle> OrderBy(string[] sorting, List<Vehicle> vehicles)
{
    return Order(sorting, vehicles, SortingFiltersVehicle);
}

//this is a generic implementation
private List<T> Order<T>(string[] sorting, List<T> vehicles, IDictionary<string, Func<T, object>> filters)
{
    if (!sorting.HasAnyValue())
        return vehicles;

    foreach (var orderby in sorting)
    {
        var key = orderby.Split("-")[0];
        if (filters.ContainsKey(key.Trim()))
        {
            var direction = orderby.Contains("desc") ? OrderByDirection.Descending : OrderByDirection.Ascending;
            vehicles = vehicles.OrderBy(filters[key], direction).ToList(); <== here is the problem
        }
    }

    return vehicles;
}

private static readonly IDictionary<string, Func<Vehicle, object>> SortingFiltersVehicle = new Dictionary<string, Func<Vehicle, object>>
{
    { "price", v => v.DiscountedPrice },
    { "make", v => v.Make },
    { "model", v => v.Model },
    { "trimline", v => v.Trimline },
};

1 个答案:

答案 0 :(得分:2)

未经测试,但这看起来应该可以工作:

private List<T> Order<T>(string[] sorting, List<T> vehicles,
    IDictionary<string, Func<T, object>> filters)
{
    if (!sorting.Any()) return vehicles;

    IOrderedEnumerable<T> sorted = null;
    foreach (var orderby in sorting)
    {
        var key = orderby.Split("-")[0];
        if (filters.ContainsKey(key.Trim()))
        {
            var desc = orderby.Contains("desc");
            var filter = filters[key];
            if (sorted == null) sorted = desc ? vehicles.OrderByDescending(filter) : vehicles.OrderBy(filter);
            else sorted = desc ? sorted.ThenByDescending(filter) : sorted.ThenBy(filter);
        }
    }

    return sorted?.ToList() ?? vehicles;
}