Order by Length then by Name - LINQ

When you are working with String arrays, a common requirement is to display the results in an ordered format. Here’s a query that shows you how to first Order the results by Length, and then by Name, using LINQ

static void Main(string[] args)
{
string[] indiaCitiesVisited = {
"Delhi", "Jodhpur", "Mumbai", "Pune", "Agra",
"Shimla", "Bengaluru", "Mysore", "Ooty",
"Jaipur", "Nagpur", "Amritsar", "Hyderabad",
"Goa", "Ahmedabad" };

IEnumerable<string> cityOrder =
indiaCitiesVisited.OrderBy(str => str.Length)
.ThenBy(str => str);
foreach (string city in cityOrder)
Console.WriteLine(city);


Console.ReadLine();
}

As you can see, we first OrderBy the length of the element and ThenBy the element itself (ascending albhabetically by Name). Remember that the ThenBy operator takes an IOrderedEnumerable<T> as the input. That’s why to create an IOrderedEnumerable, the OrderBy method is called prior to ThenBy.

OUTPUT

LINQ OrderBy ThenBy






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment:

Alex006 said...

Thank You so much!