Page 168 - CSharp/C#
P. 168
where x % 2 == 1
orderby x descending
select x * x;
// Result: 49, 25, 1
Example from wikipedia article on C# 3.0, LINQ sub-section
Example 1 uses query syntax which was designed to look similar to SQL queries.
//Example 2
IEnumerable<int> query = array.Where(x => x % 2 == 1)
.OrderByDescending(x => x)
.Select(x => x * x);
// Result: 49, 25, 1 using 'array' as defined in previous example
Example from wikipedia article on C# 3.0, LINQ sub-section
Example 2 uses method syntax to achieve the same outcome as example 1.
It is important to note that, in C#, LINQ query syntax is syntactic sugar for LINQ method syntax.
The compiler translates the queries into method calls at compile time. Some queries have to be
expressed in method syntax. From MSDN - "For example, you must use a method call to express
a query that retrieves the number of elements that match a specified condition."
Lambda expresions
Lambda Expresions are an extension of anonymous methods that allow for implicitly typed
parameters and return values. Their syntax is less verbose than anonymous methods and follows
a functional programming style.
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var numberList = new List<int> {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
var sumOfSquares = numberList.Select( number => number * number )
.Aggregate( (int first, int second) => { return first + second; } );
Console.WriteLine( sumOfSquares );
}
}
The above code will output the sum of the squares of the numbers 1 through 10 to the console.
The first lambda expression squares the numbers in the list. Since there is only 1 parameter
parenthesis may be omitted. You can include parenthesis if you wish:
.Select( (number) => number * number);
https://riptutorial.com/ 114

