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?

Papak
  • 85
  • 9
p.campbell
  • 98,673
  • 67
  • 256
  • 322

1 Answers1

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 11
    And when Jon Skeet isn't immediately available, you can use Resharper to get the same answer. – ScottS Oct 02 '09 at 21:28
  • 7
    For details of when that would be, see http://meta.stackexchange.com/questions/555/why-does-jon-skeet-never-sleep/566#566 - 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 ;) – Jon Skeet Oct 02 '09 at 21:29
  • Thanks Jon. Reading your book just this week. Thanks very much! I'll likely stick to query notation in cases like these. – p.campbell Oct 02 '09 at 21:30
  • 2
    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. – Brent Arias Dec 31 '11 at 21:54