LINQ OrderBy与ThenBy [英] LINQ OrderBy versus ThenBy

查看:141
本文介绍了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调用. (我假设您问题中的一个代码段旨在使用ThenBy.在撰写本文时,这两个代码段是相同的.)

You should definitely use ThenBy rather than multiple OrderBy calls. (I assume one of the snippets in your question was meant to use ThenBy. At the time of this writing, the two snippets are identical.)

我建议这样做:

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天全站免登陆