我可以使用Sort或OrderBy对列表进行排序.哪一个更快?两者都在使用相同的算法吗?
List<Person> persons = new List<Person>();
persons.Add(new Person("P005", "Janson"));
persons.Add(new Person("P002", "Aravind"));
persons.Add(new Person("P007", "Kazhal"));
Run Code Online (Sandbox Code Playgroud)
1.
persons.Sort((p1,p2)=>string.Compare(p1.Name,p2.Name,true));
Run Code Online (Sandbox Code Playgroud)
2.
var query = persons.OrderBy(n => n.Name, new NameComparer());
class NameComparer : IComparer<string>
{
public int Compare(string x,string y)
{
return string.Compare(x, y, true);
}
}
Run Code Online (Sandbox Code Playgroud) 与List <> OrderBy Alphabetical Order类似,我们希望按一个元素排序,然后按另一个元素排序.我们希望实现功能相当于
SELECT * from Table ORDER BY x, y
Run Code Online (Sandbox Code Playgroud)
我们有一个包含许多排序函数的类,我们没有问题按一个元素排序.
例如:
public class MyClass {
public int x;
public int y;
}
List<MyClass> MyList;
public void SortList() {
MyList.Sort( MySortingFunction );
}
Run Code Online (Sandbox Code Playgroud)
我们在列表中有以下内容:
Unsorted Sorted(x) Desired
--------- --------- ---------
ID x y ID x y ID x y
[0] 0 1 [2] 0 2 [0] 0 1
[1] 1 1 [0] 0 1 [2] 0 2
[2] 0 2 [1] 1 1 [1] 1 …Run Code Online (Sandbox Code Playgroud)