C# Sort 和 OrderBy 比较

标签 c# .net performance sorting sql-order-by

我可以使用 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} 之一 CurrentCultureOrdinalInvariantCulture )。

List<T>.Sort

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.

Enumerable.OrderBy

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/

相关文章:

c# - 如何轻松比较超过 2 个数组参数的长度?

c# - 拆分后验证电子邮件字符串

c# - .NET 有时无法加载 DLL

.net - 如何平衡和并行处理多个顺序数据流

mysql 进程陷入 "sending data"状态并挂起

c# - 为什么使用 TagBuilder 而不是 StringBuilder?

c# - Azure 登录 - 为错误请求指定回调 url

.net - Linq to objects 查找索引和求和结果

mysql - 对大量文档执行全文搜索

java - 如何加速程序? (很多慢mysql查询)