按OrderBy,ThenBy排序 [英] Sorting with OrderBy, ThenBy
问题描述
我试图根据上一个已排序的列对一个表的几个列进行排序. 对于前两列,它工作正常.但是,当我对第三列进行排序时,第二列就失去了排序.据我所知,我的foreach循环肯定有问题.这是我的排序代码:
I'm trying to sort several columns of a table depending of the previous sorted column. It works fine for the first two columns. But as soon as I sort the third column the second one loses its sort. As far as I know for now there must be a problem with my foreach loop. Here is my code for sorting:
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();
}
有什么想法吗?
更新:也许我要添加一些其他信息:
Update: Maybe I add some further information:
- @param zusortierendeListe:这是我要排序的列表,它是对象列表
- @param sortierung:这是我要排序,升序或降序的方向
对象本身就是表数据列表
The objects themselves are Lists of Tabledata
推荐答案
您正在传递Dictionary
;将Dictionary
用作IEnumerable<KeyValuePair>
时,从Dictionary
中获取值的顺序(就像您的foreach
循环一样)(可能)不是添加它们的顺序!
You're passing in a Dictionary
; the order in which you get values out of a Dictionary
when you use it as an IEnumerable<KeyValuePair>
(as your foreach
loop does) is (probably) not the order in which you added them!
您将需要使用List<KeyValuePair>
(或其他一些有序 IEnumerable<KeyValuePair>
)代替Dictionary
,甚至需要创建一个自定义类来保存字段和方向并传递的List
.
You'll need to use a List<KeyValuePair>
(or some other ordered IEnumerable<KeyValuePair>
) instead of the Dictionary
, or even create a custom class to hold the field and direction and pass a List
of that.
这篇关于按OrderBy,ThenBy排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!