180-linq-orderby-operator-and-lambda-expression-in-c

LINQ OrderBy operator we use to sort data in LINQ query. With using lambda expression (=>) example is follows:

int[] nums = new int[] { 0, 4, 2, 6, 3, 8, 3, 1 };
var result1 = nums.Where(n => n < 5).OrderBy(n => n);

another syntax for the same query is:

var result2 = nums

.Where(n => n < 5)

.OrderBy(n => n);

Syntax for LINQ OrderBy operator without lambda expression is follows:

var result = from n in nums

where n < 5

orderby n

select n;

Additionally, if we want to have distinct values from our query, example is follows:

var result3 = (from n in nums

where n < 5

orderby n

select n).Distinct();

A lambda expression is an expression on the right side of the => operator is called an expression lambda.

External links:

LINQ OrderBy Operator on Microsoft
LINQ OrderBy Operator on Stackoverflow
LINQ OrderBy Operator on Codeproject

Posted in c-sharp-code-examples

Leave a Reply

Your email address will not be published. Required fields are marked *

*