Sunday 28 May 2017

LINQ 05 Projection

A linq statement can project the properties of collection items into new items of a anonymous collection.

using System;
using System.Linq;

namespace pc.linq04
{
    class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Person(string FirstName, string LastName)
        {
            this.FirstName = FirstName;
            this.LastName = LastName;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var ppl = new Person[] { new Person("Pawel", "Chooch"),
                new Person("Magda", "Tyvoniuk"), new Person("Tomek","Chook"),
                new Person("Marin","Smartzic"), new Person("Jake","Tyvoniuk")};

            var result1 = from p in ppl
                          select new { FullName = $"{p.FirstName} {p.LastName}" };

            var result2 = ppl.Select(p => new { FullName = $"{p.FirstName} {p.LastName}});

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

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


as you can see in both the expression and method based queries we take our person class and project each of it's instances into a new anonymous object that only has a FullName property.

Of course before we project our objects we can filter them

using System;
using System.Linq;

namespace pc.linq04
{
    class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Person(string FirstName, string LastName)
        {
            this.FirstName = FirstName;
            this.LastName = LastName;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var ppl = new Person[] { new Person("Pawel", "Chooch"),
                new Person("Magda", "Tyvoniuk"), new Person("Tomek","Chooch"),
                new Person("Marin","Smartzic"), new Person("Jake","Tyvoniuk")};

            var result1 = from p in ppl
                          where p.LastName == "Chooch"
                          select new { FullName = $"{p.FirstName} {p.LastName}" };

            var result2 = ppl.Where(p=> p.LastName == "Tyvoniuk")
                             .Select(p => new { FullName = $"{p.FirstName} {p.LastName}" });

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

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


in the above we use the where function to to filter our data before projecting it.