使用OrderBy,ThenBy进行排序

时间:2012-11-23 10:56:39

标签: c# linq sorting iorderedenumerable

我正在尝试根据以前排序的列对表的几列进行排序。 它适用于前两列。但是一旦我排序第三列,第二列就会失去它的排序。据我所知,我的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的列表

2 个答案:

答案 0 :(得分:3)

你正在传递Dictionary;当您将Dictionary用作IEnumerable<KeyValuePair>时(foreach循环执行),您从List<KeyValuePair>获取值的顺序(可能)你添加它们的顺序!

您需要使用IEnumerable<KeyValuePair>(或其他一些订购的 Dictionary)代替List,或者甚至创建一个自定义类来保存字段和方向并传递{{1}}。

答案 1 :(得分:1)

另外have a look here

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

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