Thursday, April 7, 2011

Adventures in LINQ - Part 2

For this adventure, I have decided to try and simulate an outer join.  Linq does have join method, however, this method by default does an inner join.  There are many many applications where you would want to do an outer join. More specifically, I am doing a left outer join.

On the surface, the solution located at Hooked on LINQ seems a fair bit complex.  I have come up with my own solution instead.

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

namespace LinqOutterJoin
{
    class Program
    {
        static void Main(string[] args)
        {
            var element1 = new Element() { Id = 1, Name = "Element1"};
            var element2 = new Element() { Id = 2, Name = "Element2"};
            var element3 = new Element() { Id = 2, Name = "Element3"};
            var element4 = new Element() { Id = 4, Name = "Element4"};
            var element1a = new Element() { Id = 1, Name = "Element1a"};


            var elementList1 = new List { element1, element2, element3 };
            var elementList2 = new List { element1a, element4 };

            elementList1 = elementList1.Concat(elementList2.Except(elementList1)).ToList();

            elementList1.ForEach(x => Console.WriteLine(x));

        }
    }

    public class Element
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public override bool Equals(object obj)
        {
            var newObject = obj as Element;

            return this.Id == newObject.Id;
        }

        public override string ToString()
        {
            return this.Id.ToString() + " " + this.Name.ToString();
        }

        public override int GetHashCode()
        {
            return this.Id.GetHashCode();
        }
    }
}
Basically my solution makes use of the Concat and the Except methods.  Concat is pretty simple.  It takes list 2 and adds it to the end of list 1.  The Except method goes through all elements in list 1 and only returns them if they do not exist in list 2.  Sounds like an outer join to me!