Skip to content

How does ThenBy work with Comparer? #71343

Answered by heathbm
Morgfrimen asked this question in Q&A
Discussion options

You must be logged in to vote

First, in your initial chained OrderBy, you can drop the ToList().

var comparerList = list.OrderBy(x => x.Name).ToList().OrderBy(x => x, new SiteMapComparer());
to
var comparerList = list.OrderBy(x => x.Name).OrderBy(x => x, new SiteMapComparer());

To answer the ThenBy question:

Essentially, ThenBy does not perform a complete OrderBy again, otherwise, it would just duplicate OrderBy().
OrderBy will order the list by a key (x.Name in this case).
ThenBy allows you to apply subsequent ordering on the items belonging to the same key.
Since your provided list has no duplicate Name keys, the SiteMapComparer will never be called as there is only 1 item to sort, so it is skipped.

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@Clockwork-Muse
Comment options

Answer selected by Morgfrimen
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants