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);
and
tmp = invoices.InvoiceCollection
.OrderBy(sort1 => sort1.InvoiceOwner.LastName)
.ThenBy(sort2 => sort2.InvoiceOwner.FirstName)
.ThenBy(sort3 => sort3.InvoiceID);
Which is the correct approach if I wish to order by 3 items of data?
You should definitely use
ThenByrather than multipleOrderBycalls.I would suggest this:
Note how you can use the same name each time. This is also equivalent to:
If you call
OrderBymultiple 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) writewhich would be equivalent to
as the sort order is stable, but you absolutely shouldn’t:
OrderBywas designed to be used.The point of
OrderByis to provide the “most important” ordering projection; then useThenBy(repeatedly) to specify secondary, tertiary etc ordering projections.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.