使用 OrderBy 和 ThenBy 进行排序

3

我正在尝试根据之前排序的列对表格的几列进行排序。 对于前两列,它运行得很好。但是一旦我对第三列进行排序,第二列就会失去它的排序。据我目前所知,我的foreach循环必须存在问题。这是我用来排序的代码:

public List<object> inhaltSortieren(List<object> zuSortierendeListe, Dictionary<string, SortierRichtung> sortierung)
{
    IOrderedEnumerable<object> sortierteListe = null;
    if (sortierung.First().Value == SortierRichtung.asc)
        sortierteListe = zuSortierendeListe.OrderBy(x => x.GetType().GetProperty(sortierung.First().Key).GetValue(x, null));
    else if (sortierung.First().Value == SortierRichtung.desc)
        sortierteListe = zuSortierendeListe.OrderByDescending(x => x.GetType().GetProperty(sortierung.First().Key).GetValue(x, null));
    bool first = true;
    foreach (KeyValuePair<string, SortierRichtung> spalte in sortierung)
    {
        if (first)
        {
            first = false;
            continue;
        }
        if (spalte.Value == SortierRichtung.asc)
            sortierteListe = sortierteListe.ThenBy(x => x.GetType().GetProperty(spalte.Key).GetValue(x, null));
        else if (spalte.Value == SortierRichtung.desc)
            sortierteListe = sortierteListe.ThenByDescending(x => x.GetType().GetProperty(spalte.Key).GetValue(x, null));
    }

    return sortierteListe.ToList();
 }

有什么想法吗?

更新:也许我可以添加一些进一步的信息:

  • @param zusortierendeListe:这是我想要排序的列表,它是一个对象列表
  • @param sortierung:这是我想要排序的方向,升序或降序

这些对象本身是Tabledata列表


3
你的代码在概念上存在问题 - 你把一个 Dictionary<,> 当作了一个有序列表。但它并不是有序的。 - Jon Skeet
尝试将Dictionary<string, SortierRichtung>替换为List<Tuple<string,SortierRichtung>>,例如。 - Lukas Winzenried
2个回答

3
你正在传递一个Dictionary,当你将它作为IEnumerable(就像你的foreach循环一样)使用时,从Dictionary中获取值的顺序(可能)不是你添加键值对的顺序!你需要使用一个List(或其他有序的IEnumerable),而不是Dictionary,甚至可以创建一个自定义类来保存字段和方向,并传递一个List。

1

同时在这里看一下

只是为了使您的代码更加清晰。您可以将所有内容放入 for-each 循环中,或者保留原样,但然后在您的代码中使用 sortierung.Skip(1),因为您已经使用了第一个条目。我还根据先前的评论将 Dictionary 参数更改为 IEnumerable>。

    object GetValue(object value, string name)
    {
        return value.GetType().GetProperty(name).GetValue(value, null);
    }

    public List<object> SortContent(List<object> listToSort, Tuple<string, SortDirection>[] sortInfos)
    {
        if (sortInfos == null || sortInfos.Length == 0)
             return listToSort;

        IOrderedEnumerable<object> sortedList = null;

        foreach (var column in sortInfos)
        {
            Func<object, object> sort = x => GetValue(x, column.Key);

            bool desc = column.Value == SortDirection.Descending;

            if (sortedList == null)
                sortedList = desc ? listToSort.OrderByDescending(sort) : listToSort.OrderBy(sort);
            else
                sortedList = desc ? sortedList.ThenByDescending(sort) : sortedList.ThenBy(sort);
        }

        return sortedList.ToList();
    }

如果他将一个Dictionary传递给IEnumerable参数,这仍然会出现错误。(除此之外是一些好的想法 :)) - Rawling

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接