>Query keywords – orderby

>

orderby: Is used for sorting the records. In comprehension syntax it is just like we use it in SQL. i.e:

from c in Customers
orderby c.Country, c.CompanyName descending
select c

Here we are ordering by Country (default ascending) and then by CompanyName in descending order.

In method syntax there are 4 methods:

OrderBy()
OrderByDescending()
ThenBy()
ThenByDescending()

Using method syntax above sample would be written as:

Customers
  .OrderBy( c => c.Country )
  .ThenByDescending( c => c.CompanyName )
  .Select( c => c)

All 4 methods support a custom comparison method as a second parameter (for example you could create a method that instead of widely known alphabetical sort, sorts the strings based on a custom ordering – "10" comes after "2").

Here is a sample modified from LinqPad’s OrderBy sample:

string[] strings = { "Tom", "Çetin",
   "I come before i", "Can", "in",
   "Dick", "Harry", "Mary", "Jay",
   "ş is between s and t", "smith"};

strings.OrderBy (n => n, StringComparer.Create( new System.Globalization.CultureInfo("tr-TR"), true))
    .Dump ("Case insensitive ordering based on Turkish alphabet");

This second parameter is not supported in Linq to SQL.

About cetinbasoz

A developer working primarily with C#,F#,VFP,SQL server, Silverlight,Linq ...
This entry was posted in Uncategorized. Bookmark the permalink.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s