Linq Array Order-By

Linq Array Order-By

Linq Sort Array Example. Here is very simple example of ordering an array of string using Linq expression. We will sort array of string.

C# Linq sort array ascending.

string[] arrOfStrings = new string[]
	{
	    "Linq",
	    "WCF",
	    "WPF",
	    "SilverLight",
	    ".Net",
		"IIS7",
		"HTML5",
		"Android"
	};
	// Linq expression to sort an array of strings.
	var sortResults = from s in arrOfStrings
		   orderby s
		   select s;

	foreach (string str in sortResults)
	{
	    Console.WriteLine(str);
	}
Output
.Net
Android
HTML5
IIS7
Linq
SilverLight
WCF
WPF

Above example uses LINQ expression as:

var sortResults = from s in arrOfStrings
		   orderby s
		   select s;

The default order by clause does sorting in ascending order.

Linq Sort order by descending.

Let’s sort an array of string in descending order. It will reverse the array output in result.

string[] arrOfStrings = new string[]
	{
	    "Linq",
	    "WCF",
	    "WPF",
	    "SilverLight",
	    ".Net",
		"IIS7",
		"HTML5",
		"Android"
	};
	
	var sortResults = from str in arrOfStrings
		   orderby str descending
		   select str;

	foreach (string str in sortResults)
	{
	    Console.WriteLine(str);
	}
Output :
WPF
WCF
SilverLight
Linq
IIS7
HTML5
Android
.Net

Tags:

Linq Array Order-Byc# arraylistC# ArrayList Search using Linq Extension OfType MethodLinq Split String To ListLearn Linq Step By StepLinq Group By Multiple ColumnsHow To Declare and access array of string in C#One dimensional array example C#.net VB.netLinq Inner JoinLinq Distinct ListLinq Get Duplicate Count Of Words From String

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.