How IEnumerable is working in C#

-

A simple demonstration of how Enumerable works. I assume that you have knowledge about;

  1. Extension method
  2. Function delegate
Consider the following example;

Let’s filter person class having person.Age greater than 3.
  1. public class Person  
  2. {  
  3.     public int Age;  
  4. }  
  5. class Program  
  6. {  
  7.     static void Main(string[] args)  
  8.     {  
  9.   
  10.         Func<Person, bool> ff = sady;  
  11.             Person[] ee = new Person[]
  12.           {
  13.              new Person { Age = 1 }, 
  14.             new Person { Age = 2 },
  15.              new Person { Age = 3 },
  16.              new Person { Age = 4 },
  17.              new Person { Age = 5 } 
  18.          };  
  19.         IEnumerable<Person> pa = ee.Where(sady);  
  20.          //(or) IEnumerable<Person> pa = ee.Where(ff);  
  21.         // (or)IEnumerable<Person> pa = ee.Where(s=>s.Age >3);  
  22.   
  23.         foreach (Person item in pa)  
  24.         {  
  25.             Console.WriteLine(item.Age);  
  26.         }  
  27.         Console.Read();  
  28.     }  
  29.     public static bool sady(Person a)  
  30.     {  
  31.         if (a.Age > 3) return true;  
  32.         else return false;  
  33.     }  
  34. }  
  35. output is
  36. 4
  37. 5
  • The syntax for IEnumerable.where is;
    1. Enumerable.Where<TSource> Method (IEnumerable<TSource>, Func<TSource, Boolean>)  

    So the normal syntax according to above example is:
    1. Enumerable.Where (this IEnumerable< Person >, Func< Person, Boolean>)  
    Its takes Person class as extension method and a Func delegate as a parameter.

  • What is Func<> delegate

    Consider is Func<int,bool>. It’s nothing but a delegate signature with one input of type int
    And one output of type bool.

    This Func<int,bool> can wrap any method with one input of type int. And one output of type bool.

    So According this syntax:
    1. Enumerable.Where (this IEnumerable< Person >, Func< Person, Boolean>)  
    Func< Person, Boolean>) can accept.
    1. public static bool sady(Person a)  
    2. {  
    3.    if (a.Age > 3) return true;  
    4.    else return false;  
    5. }  
So you are passing the person class and the action (a.Age > 3) that should be performed on each individual variable.

So IEnumerable check the condition as per user requirement and group the result that satisfies the condition and return to user.

Summery

IEnumerable actually applies the filter that is given as parameter by function delegate ( Func< Person, Boolean>) for each items in the collection and then groups the result that passes the condition then returns the result to user.
  1. IEnumerable<Person> pa = ee.Where(s=>s.Age >3);  
(s=>s.Age >3) this is Lambda expression that takes one input of type int and return bool.
Ebook Download
View all
Learn
View all