More complex left outer join

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 joinedGroup 
                         from joined in joinedGroup.DefaultIfEmpty()
                         select new { owner, joined }).Where(match => match.joined == null).Select(arg => arg.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;
        }
    }
}

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s