linq left outer joins

linq left outer joins

Join when using LINQ. There are no keywords defined in C#, we have to use DefaultIfEmpty() function to get the desired result.
private void LeftOuterJoins()
        {
            Tag = "Left Outer Joins";
            Person bhaumik = new Person { FirstName = "Bhaumik", LastName = "Patel" };
            Person hardik = new Person { FirstName = "Hardik", LastName = "Patel" };
            Person manan = new Person { FirstName = "Manan", LastName = "Bhavsar" };
            Person vishal = new Person { FirstName = "Vishal", LastName = "Gorasia" };

            Pet patel = new Pet { Name = "Patel", Owner = hardik };
            Pet hardik1 = new Pet { Name = "Hardik", Owner = hardik };
            Pet sonu = new Pet { Name = "Sonu", Owner = manan };
            Pet gorasia = new Pet { Name = "Gorasia", Owner = hardik };
            Pet patel1 = new Pet { Name = "Patel", Owner = bhaumik };

            // Create two lists.
            List<Person> people = new List<Person> { bhaumik, hardik, manan, vishal };
            List<Pet> pets = new List<Pet> { patel, hardik1, sonu, gorasia, patel1 };

            var query = from person in people
                        join pet in pets on person equals pet.Owner into gj
                        from subpet in gj.DefaultIfEmpty()
                        select new { person.FirstName, PetName = (subpet == null ? String.Empty : subpet.Name) };

            grdView.DataSource = query.ToList();
            grdView.DataBind();
        }

Person and Pet Class
class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    class Pet
    {
        public string Name { get; set; }
        public Person Owner { get; set; }
    }


SEE ALL LINQ JOINS

Download All Linq Joins
linq left outer joins linq left outer joins Reviewed by Bhaumik Patel on 8:12 PM Rating: 5