Friday, 26 May 2017

LINQ 03 Where

the where class is the bread and butter of linq, it lets you filter you're results. You can fully leverage any c# comparison you can think of ==, !=, >, <. <=, >= or &&, ||, String.IsNullOrEmpty, etc.

using System;
using System.Linq;

namespace pc.linq02
{
    class Program
    {
        static void Main(string[] args)
        {
            var nums = Enumerable.Range(1, 20);

            var result1 = from n in nums
                          where n % 2 == 0 && n % 3 == 0
                          select n;

            Array.ForEach(result1.ToArray(), n => Console.Write(n + " "));
            Console.WriteLine();

            var result2 = from n in nums
                          where n % 2 == 0
                          where n % 3 == 0
                          select n;

            Array.ForEach(result2.ToArray(), n => Console.Write(n + " "));
            Console.WriteLine();
        }
    }
}


now as we demonstrated we can leverage multiple where clauses which are the equivalent to the AND operator. Now as always whatever we can do in expressive linq we can accomplish in method based linq

using System;
using System.Linq;

namespace pc.linq02
{
    class Program
    {
        static void Main(string[] args)
        {
            var nums = Enumerable.Range(1, 20);

            var result1 = nums.Where(n => n % 2 == 0 && n % 3 == 0);

            Array.ForEach(result1.ToArray(),  n => Console.Write(n + " "));
            Console.WriteLine();

            var result2 = nums.Where(n=>n%2 == 0).Where(n=> n %3 == 0);

            Array.ForEach(result2.ToArray(),  n => Console.Write(n + " "));
            Console.WriteLine();
        }
    }
}


we can even encampment our where clause login into functions that return a bool

using System;
using System.Linq;

namespace pc.linq02
{
    class Program
    {
        static void Main(string[] args)
        {
            var nums = Enumerable.Range(1, 20);

            var result1 = nums.Where(n => IsEven(n) && IsMultipleOfThree(n));

            Array.ForEach(result1.ToArray(),  n => Console.Write(n + " "));
            Console.WriteLine();

            var result2 = from n in nums
                          where IsEven(n)
                          where IsMultipleOfThree(n)
                          select n;

            Array.ForEach(result2.ToArray(), n => Console.Write(n + " "));
            Console.WriteLine();
        }

        static bool IsEven(int i) return i % 2 == 0; }

        static bool IsMultipleOfThree(int i) return i % 3 == 0; }
    }
}


above we demonstrate the use of functions inside of our linq statements for both method and expression based queries.