LINQ comes in two flavors
- "Expression" based which looks like upside down SQL
- "Method" based which is made up of extension methods found in the IEnumerable or IQueryable interfaces
class Program
{
static void Main(string[] args)
{
//Create Number
array
int[] Numbers = Enumerable.Range(0, 20).ToArray();
//use foreach
to get even numbers
List<int> even1 = new List<int>();
foreach (int n in Numbers)
if (n % 2 == 0)
even1.Add(n);
//use
expression linq to get even numbers
IEnumerable<int>
even2 = from i in Numbers
where i % 2 == 0
select i;
//use method
based linq to get even numbers
IEnumerable<int>
even3 = Numbers.Where(i => i % 2 == 0);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
namespace pc.linq00
{
class Program
{
static void Main(string[] args)
{
//Create Number
array
int[] Numbers = Enumerable.Range(0, 20).ToArray();
//use foreach
to get even numbers
var even1 = new List<int>();
foreach (int n in Numbers)
if (n % 2 == 0)
even1.Add(n);
//use
expression linq to get even numbers
var even2 = from i in Numbers
where i % 2 == 0
select i;
//use method
based linq to get even numbers
var even3 = Numbers.Where(i => i % 2 == 0);
foreach (var n in even1)
Console.Write(n + " ");
Console.WriteLine("\n");
foreach (var n in even2)
Console.Write(n + " ");
Console.WriteLine("\n");
foreach (var n in even3)
Console.Write(n + " ");
Console.WriteLine("\n");
}
}
}
When you run the application and step through it you'll notice that when the foreach statement executes the execution keeps transferring between the foreach statement and the where clause in the LINQ query. This is because the LINQ query isn’t actually executed until the container (in this case our even2 and even3 collections) is used. This is called deferred execution.