tags:

views:

252

answers:

1

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?

+7  A: 

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
And when Jon Skeet isn't immediately available, you can use Resharper to get the same answer.
ScottS
For details of when that would be, see http://meta.stackoverflow.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
Thanks Jon. Reading your book just this week. Thanks very much! I'll likely stick to query notation in cases like these.
p.campbell
In that case see P296-300 :)
Jon Skeet