【发布时间】:2011-01-23 12:20:11
【问题描述】:
如何根据两个不同的条件进行排序?
例如,我有如下人员对象:
Person 具有属性 FirstName(字符串)、LastName 和 Rank(整数)。
示例数据如下:
Xavier Smith 1
Alexander Smith 2
Alexander Smith 1
Bob Hawke 2
它应该按名字的字母顺序排序,然后按排名,例如结果:
Alexander Smith 1
Alexander Smith 2
Bob Hawke 2
Xavier Smith 1
到目前为止,我已经尝试了以下方法,但无法正常工作:
peopleList 是List<Person>
peopleList.Sort(new Comparison<Person>((x,y) => x.Rank.CompareTo(y.Rank)));
peopleList.Sort(new Comparison<Person>((x, y) => string.Compare(x.Name, y.Name)));
谢谢
编辑:为了避免过多地更改我的代码,我真的想保留列表,如果我将上面的行更改为:
peopleList.OrderBy(person => person.FirstName).ThenBy(person => person.Rank).ToList();
会给出刚刚正确排序的完全相同的列表,对吗?
【问题讨论】: