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

1 comment: