LINQ OrderBy 与 ThenBy [英] LINQ OrderBy versus ThenBy

查看:25
本文介绍了LINQ OrderBy 与 ThenBy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释一下两者之间的区别:

Can anyone explain what the difference is between:

tmp = invoices.InvoiceCollection
              .OrderBy(sort1 => sort1.InvoiceOwner.LastName)
              .OrderBy(sort2 => sort2.InvoiceOwner.FirstName)
              .OrderBy(sort3 => sort3.InvoiceID);

tmp = invoices.InvoiceCollection
              .OrderBy(sort1 => sort1.InvoiceOwner.LastName)
              .ThenBy(sort2 => sort2.InvoiceOwner.FirstName)
              .ThenBy(sort3 => sort3.InvoiceID);

如果我想按 3 项数据进行排序,哪种方法是正确的?

Which is the correct approach if I wish to order by 3 items of data?

推荐答案

你应该绝对使用 ThenBy 而不是多个 OrderBy 调用.

You should definitely use ThenBy rather than multiple OrderBy calls.

我建议这样做:

tmp = invoices.InvoiceCollection
              .OrderBy(o => o.InvoiceOwner.LastName)
              .ThenBy(o => o.InvoiceOwner.FirstName)
              .ThenBy(o => o.InvoiceID);

注意如何每次都使用相同的名称.这也相当于:

Note how you can use the same name each time. This is also equivalent to:

tmp = from o in invoices.InvoiceCollection
      orderby o.InvoiceOwner.LastName,
              o.InvoiceOwner.FirstName,
              o.InvoiceID
      select o;

如果多次调用 OrderBy,它将有效地将序列完全重新排序三次......因此最终调用将有效地成为主导调用.您可以(在 LINQ to Objects 中)编写

If you call OrderBy multiple times, it will effectively reorder the sequence completely three times... so the final call will effectively be the dominant one. You can (in LINQ to Objects) write

foo.OrderBy(x).OrderBy(y).OrderBy(z)

相当于

foo.OrderBy(z).ThenBy(y).ThenBy(x)

因为排序顺序是稳定的,但你绝对不应该:

as the sort order is stable, but you absolutely shouldn't:

  • 很难阅读
  • 它表现不佳(因为它重新排列了整个序列)
  • 它可能在其他提供程序(例如 LINQ to SQL)中工作
  • 这基本上不是 OrderBy 的设计用途.
  • It's hard to read
  • It doesn't perform well (because it reorders the whole sequence)
  • It may well not work in other providers (e.g. LINQ to SQL)
  • It's basically not how OrderBy was designed to be used.

OrderBy 的重点是提供最重要"的排序投影;然后使用 ThenBy(重复)指定二级、三级等排序投影.

The point of OrderBy is to provide the "most important" ordering projection; then use ThenBy (repeatedly) to specify secondary, tertiary etc ordering projections.

实际上,可以这样想:OrderBy(...).ThenBy(...).ThenBy(...) 允许您为任意两个对象构建单个复合比较,然后使用该复合比较对序列进行一次排序.这几乎肯定是您想要的.

Effectively, think of it this way: OrderBy(...).ThenBy(...).ThenBy(...) allows you to build a single composite comparison for any two objects, and then sort the sequence once using that composite comparison. That's almost certainly what you want.

这篇关于LINQ OrderBy 与 ThenBy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆