Left join in LINQ

Do you want to retrieve people that doesn’t own a pet? Just take a look at this 🙂

using System.Collections.Generic;

namespace LeftJoin
{
    using System;
    using System.Linq;

    class Program
    {
        static void Main(string[] args)
        {
            var johnny = new Person("Johnny");
            var david = new Person("David");
            var michael = new Person("Michael");

            var owners = new List<Person> { johnny, david, michael };
            var pets = new List<Pet> { new Pet("Flocky", johnny), new Pet("Choo choo", david)};

            var noPets = from owner in owners join p in pets on owner equals p.Owner into joined where !joined.Any() select owner;                        

            foreach (var person in noPets)
            {
                Console.WriteLine(person);
            }
        }
    }

    internal class Person
    {
        public Person(string name)
        {
            this.Name = name;
        }

        public string Name { get; set; }

        public override string ToString()
        {
            return Name;
        }
    }

    internal class Pet
    {
        private readonly string name;

        private readonly Person owner;

        public Pet(string name, Person owner)
        {
            this.name = name;
            this.owner = owner;
        }

        public string Name
        {
            get
            {
                return this.name;
            }
        }

        public Person Owner
        {
            get
            {
                return this.owner;
            }
        }

        public override string ToString()
        {
            return Name;
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s