This article will show you , how could we use Predicate , Anonymous method and Lambdas with LINQ to find out all odd numbers from a range of number.
If we have a range of number from 1 to 20 and we want to find odd among them using LINQ .
We have three options for that
- Calling a Predicate
- Anonymous Method
- Lambda

So here we can see that we need to pass a predicate to evaluate the condition.
Calling a Predicate
Function we will pass as predicate is as below
staticvoid Main(string[] args)
{
var result = from r in
Enumerable.Range(1, 20).Where(GetOdd)
select r;
foreach (var r in result)
Console.WriteLine(r);
Console.ReadKey(true);
}
We will pass this function as predicate to find odd numbers from the range of numbers.
var result = from r in
Enumerable.Range(1, 20).Where(GetOdd)
select r;
Program.cs
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
namespace ConsoleApplication25
{
classProgram
{
staticvoid Main(string[] args)
{
var result = from r in
Enumerable.Range(1, 20).Where(GetOdd)
select r;
foreach (var r in result)
Console.WriteLine(r);
Console.ReadKey(true);
}
staticboolGetOdd(int number)
{
if (number % 2 != 0)
return true;
else
return false;
}
}
}
Output

Using Anonymous Method
We can use anonymous method also
var result = from r in
Enumerable.Range(1, 20).Where(delegate(int number)
{
if (number % 2 != 0)
return true;
return false; })
select r;
Anonymous method is taking an input parameter and returning a Boolean value.
Program.cs
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
namespace ConsoleApplication25
{
classProgram
{
staticvoid Main(string[] args)
{
var result = from r in
Enumerable.Range(1, 20).Where(delegate(int number)
{
if (number % 2 != 0)
return true;
return false; })
select r;
foreach (var r in result)
Console.WriteLine(r);
Console.ReadKey(true);
}
}
}
Output
![clip_image008[1] clip_image008[1]](http://beyondrelational.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/ashish/clip_5F00_image0081_5F00_thumb_5F00_5404B686.jpg)
Using Lambda
To make our query more readable in version 3.0 and onwards we can use Lambda instead of anonymous method also.
var result = from r in
Enumerable.Range(1, 20).Where(num =>num%2!=0)
select r;
Lambda is very simple returning true when reminder is 0.
Program.cs
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
namespace ConsoleApplication25
{
classProgram
{
staticvoid Main(string[] args)
{
var result = from r in
Enumerable.Range(1, 20).Where(num =>num%2!=0)
select r;
foreach (var r in result)
Console.WriteLine(r);
Console.ReadKey(true);
}
}
}
Output
