LINQ: dot notation equivalent for JOIN
Asked Answered
D

1

42

Consider this LINQ expression written using query notation:

 List<Person> pr = (from p in db.Persons
                     join e in db.PersonExceptions
                     on p.ID equals e.PersonID
                     where e.CreatedOn >= fromDate
                     orderby e.CreatedOn descending
                     select p)
                   .ToList();

Question: how would you write this LINQ expression using dot notation?

Doubletongue answered 2/10, 2009 at 21:18 Comment(0)
S
79

Like this:

List<Person> pr = db.Persons
                    .Join(db.PersonExceptions,
                          p => p.ID,
                          e => e.PersonID,
                          (p, e) => new { p, e })
                    .Where(z => z.e.CreatedOn >= fromDate)
                    .OrderByDescending(z => z.e.CreatedOn)
                    .Select(z => z.p)
                    .ToList();

Note how a new anonymous type is introduced to carry both the p and e bits forward. In the specification, query operators which do this use transparent identifiers to indicate the behaviour.

Scopophilia answered 2/10, 2009 at 21:23 Comment(4)
And when Jon Skeet isn't immediately available, you can use Resharper to get the same answer.Comprehension
For details of when that would be, see meta.stackexchange.com/questions/555/… - oh, and C# in Depth goes into all of this as well, of course. It's like having a miniature version of me on your bookshelf ;)Scopophilia
Thanks Jon. Reading your book just this week. Thanks very much! I'll likely stick to query notation in cases like these.Doubletongue
I'd like to see the dot notation for two joins (i.e. three sources). I'm not talking about multiple join conditions, I'm talking about multiple joins. A long google hunt has turned up no examples.Forrest

© 2022 - 2024 — McMap. All rights reserved.