如何根据两个不同的标准进行排序?
例如,我有人物对象,如:
Personwith properties FirstName(string)LastName,和Rank(int).
像这样的示例数据:
Xavier Smith 1
Alexander Smith 2
Alexander Smith 1
Bob Hawke 2
Run Code Online (Sandbox Code Playgroud)
它应按字母顺序排序FirstName,然后按排名排序,例如:
Alexander Smith 1
Alexander Smith 2
Bob Hawke 2
Xavier Smith 1
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已经尝试了以下内容,但它无法正常工作:
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)));
Run Code Online (Sandbox Code Playgroud)
谢谢
编辑:为了避免更改我的代码,我真的想保留列表,如果我将上面的行更改为:
peopleList.OrderBy(person => person.FirstName).ThenBy(person => person.Rank).ToList();
Run Code Online (Sandbox Code Playgroud)
会给出完全相同的列表,只是正确排序,对吗?
Ahm*_*eed 21
LINQ方法
var result = peopleList.OrderBy(p => p.FirstName).ThenBy(p => p.Rank);
Run Code Online (Sandbox Code Playgroud)
这将返回一个IEnumerable<T>.如果你真的需要在最后List<T>添加一个.ToList().
如果要使用该Sort方法,则需要编写自定义比较器.
编辑:使用ToList()返回一个新列表.如果要对现有列表进行排序,则应使用Sort不返回列表但在当前列表上操作的void方法(这是一种方法).
排序/比较方法
使用: list.Sort(new PersonComparer());
这是比较器代码.它是从MSDN示例改编的,所以我建议阅读他们用来理解为什么这样结构的注释.
public class PersonComparer : IComparer<Person>
{
public int Compare(Person x, Person y)
{
if (x == null)
{
if (y == null)
{
return 0;
}
else
{
return -1;
}
}
else
{
if (y == null)
{
return 1;
}
else
{
int retval = x.FirstName.CompareTo(y.FirstName);
if (retval != 0)
{
return retval;
}
else
{
return x.Rank.CompareTo(y.Rank);
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
其他答案似乎比这更优雅,它们让我感觉更像是一个菜鸟,但是如果你理解如何排序这样,你可以以任何方式排序任何类型的列表而不需要知道任何东西.并且不需要编写一个全新的类(尽管如果在代码的其他部分中对其他类似的列表进行排序,编写一个比较器类会很有用).
peopleList.Sort((x, y) =>
{
int compare = x.FirstName.CompareTo(y.FirstName);
if (compare != 0)
return compare;
compare = x.Rank.CompareTo(y.Rank);
if (compare != 0)
return compare;
return x.LastName.CompareTo(y.LastName);
});
Run Code Online (Sandbox Code Playgroud)
您实际上非常接近就地排序 lambda 语法。您只是忽略了 lambda 可以包含在其自己的范围内的事实:
peopleList.Sort(new Comparison<Person>((x,y) =>
{
int result = x.FirstName.CompareTo(y.FirstName);
return (result != 0) ? result : x.Rank.CompareTo(y.Rank);
}));
Run Code Online (Sandbox Code Playgroud)
这比自己写要省力一点IComparer<Person>!