Elisabeth
Elisabeth

Reputation: 21206

Left Outer join with Linq without DefaultIfEmpty

I am trying to use this sample:

What I want is the ONLY return of:´the Book with Id = 2.

 new Book{BookID=2, BookNm=".NET and COM for Newbies"},

I want only those book(s) which has no Orders.

When I remove the DefaultIfEmpty() it does not work either.

UPDATE

 Person magnus = new Person { FirstName = "Magnus", LastName = "Hedlund" };
            Person terry = new Person { FirstName = "Terry", LastName = "Adams" };
            Person charlotte = new Person { FirstName = "Charlotte", LastName = "Weiss" };
            Person arlene = new Person { FirstName = "Arlene", LastName = "Huff" };

            Pet barley = new Pet { Name = "Barley", Owner = terry };
            Pet boots = new Pet { Name = "Boots", Owner = terry };
            Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte };
            Pet bluemoon = new Pet { Name = "Blue Moon", Owner = terry };
            Pet daisy = new Pet { Name = "Daisy", Owner = magnus };

            // Create two lists.
            List<Person> people = new List<Person> { magnus, terry, charlotte, arlene };
            List<Pet> pets = new List<Pet> { barley, boots, whiskers, bluemoon, daisy };

            var query = from person in people
                        join pet in pets on person equals pet.Owner into gj                       
                        where !gj.Any()
                        select person;

I just tried this code and it seems it works!

I get returned the person Arlene she has no pets!

Can somene confirm that this is a known approach? I just invented it LOL

Upvotes: 0

Views: 910

Answers (1)

Kapol
Kapol

Reputation: 6463

You are misinterpreting how left join works. a LEFT JOIN b will return all items from a, regardless if they have matching items in b. If I correctly understand your question, you don't need a join here at all, because you don't want any additional data from bookOrders. You can just use LINQ's All extension method:

var query = bookList.Where(b => bookOrders.All(o => o.BookId != b.BookId).ToList();

This will return all books for which no book order contains the book's ID. I'm basing the names on the linked article.

Upvotes: 1

Related Questions