我可以使用 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"));
1.
persons.Sort((p1,p2)=>string.Compare(p1.Name,p2.Name,true));
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);
}
}
最佳答案
不,它们不是同一种算法。对于初学者,LINQ OrderBy
记录为稳定(即,如果两个项目具有相同的 Name
,它们将按其原始顺序出现)。
这还取决于您是缓冲查询还是多次迭代查询(LINQ-to-Objects,除非您缓冲结果,将根据 foreach
重新排序)。
对于 OrderBy
查询,我也很想使用:
OrderBy(n => n.Name, StringComparer.{yourchoice}IgnoreCase);
(对于 {yourchoice}
之一 CurrentCulture
、 Ordinal
或 InvariantCulture
)。
This method uses Array.Sort, which uses the QuickSort algorithm. This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.
This method performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved. In contrast, an unstable sort does not preserve the order of elements that have the same key. sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.
关于C# Sort 和 OrderBy 比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1832684/