This blog is based on the article written by Mahesh Chand on using LINQ to filter sets of integers. After reading Mahesh's article, I decided to have a little fun with LINQ myself.
Say we start with the following set of integers:
static int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 };
What if we want all the odd numbers in this set using LINQ? We can use the mod function to filter out the set we are interested in.
static void OddNumbers()
{
var oddNumberResult = from number in intArray where number % 2
== 1 select number;
Console.WriteLine("The odd numbers from 1-25: ");
Console.WriteLine("=====================");
foreach (var result in oddNumberResult)
{
Console.WriteLine(result);
}
Console.WriteLine("======================");
Console.ReadLine();
}

Let's turn it up a notch. What if we want all the perfect squares? We can use the square root in combination with rounding to figure out if a number in the set is a perfect square:
static void PerfectSquares()
{
var perfectSquaresResult = from number in intArray where
(int)(Math.Sqrt((double)number)*10) == ((int)(Math.Sqrt((double)
number)))*10 select number;
Console.WriteLine("The Perfect Squares of numbers from 1-25: ");
Console.WriteLine("=====================");
foreach (var result in perfectSquaresResult)
{
Console.WriteLine(result);
}




Hussain AhmedPosted Mar 27, 2014, 4:59 AM
Nice Work