A simple demonstration of how Enumerable works. I assume that you have knowledge about;
- Extension method
- Function delegate
Let’s filter person class having person.Age greater than 3.
- public class Person
- {
- public int Age;
- }
- class Program
- {
- static void Main(string[] args)
- {
- Func<Person, bool> ff = sady;
- Person[] ee = new Person[]
- {
- new Person { Age = 1 },
- new Person { Age = 2 },
- new Person { Age = 3 },
- new Person { Age = 4 },
- new Person { Age = 5 }
- };
- IEnumerable<Person> pa = ee.Where(sady);
- //(or) IEnumerable<Person> pa = ee.Where(ff);
- // (or)IEnumerable<Person> pa = ee.Where(s=>s.Age >3);
- foreach (Person item in pa)
- {
- Console.WriteLine(item.Age);
- }
- Console.Read();
- }
- public static bool sady(Person a)
- {
- if (a.Age > 3) return true;
- else return false;
- }
- }
- output is
- 4
- 5
- The syntax for IEnumerable.where is;
- Enumerable.Where<TSource> Method (IEnumerable<TSource>, Func<TSource, Boolean>)
So the normal syntax according to above example is:Its takes Person class as extension method and a Func delegate as a parameter.- Enumerable.Where (this IEnumerable< Person >, Func< Person, Boolean>)
- 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:Func< Person, Boolean>) can accept.- Enumerable.Where (this IEnumerable< Person >, Func< Person, Boolean>)
- public static bool sady(Person a)
- {
- if (a.Age > 3) return true;
- else return false;
- }
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.
- IEnumerable<Person> pa = ee.Where(s=>s.Age >3);

Join the conversation! Your thoughts help the community grow.