Thursday 25 May 2017

LINQ 02 IEnumerable

We can create our own collections that can be leveraged by LINQ as long as we implement the IEnumerable or IQueryable interface.

so let's do just that and implement the IEnumerable Interface

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace pc.linq01
{
    class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Fullname {
            get { return $"{FirstName} {LastName}"; } }

        public Person(string FirstName, string LastName)
        {
            this.FirstName = FirstName;
            this.LastName = LastName;
        }
    }

    class People : IEnumerable<Person>
    {
        Person[] ppl;
        public IEnumerator<Person> GetEnumerator()
        {
            for (int i = 0; i < ppl.Length; i++)
                yield return ppl[i];
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public People(params Person[] ppl) {
            this.ppl = ppl;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var ppl = new People(new Person("Pawel", "Chooch"),
                new Person("Magda","Tyvoniuk"),
                new Person("Jake","Tyvonuik"),
                new Person ("Adam","Chooch"));

            var choochs1 = from p in ppl
                           where p.LastName == "Chooch"
                           select p;

            var choochs2 = ppl.Where(p => p.LastName == "Chooch");

            foreach (var c in choochs1)
                Console.Write(c.Fullname+ " ");
            Console.WriteLine("\n");

            foreach (var c in choochs2)
                Console.Write(c.Fullname + " ");
            Console.WriteLine("\n");
        }
    }
}


nothing we have't done before, we leverage the yield keyword for simplicity sake, but just by implementing the IEnumerable interface we can now use linq to query our collection.