LINQ “ThenBy” example.

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?

 

Ans:

You should definitely use ThenBy rather than multiple OrderBy calls.  (2nd query)

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

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

If you call OrderBy multiple times, it will effectively reorder the sequence completely three times.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s