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)


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.


LINQ OrderBy ThenBy

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 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!