Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: dot notation equivalent for JOIN

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?

like image 774
p.campbell Avatar asked Oct 02 '09 21:10

p.campbell


People also ask

Is LINQ join inner or outer?

When you use the LINQ join clause in the query expression syntax to combine two sets of related information, you perform an inner join.

What type of join is LINQ join?

In LINQ, an inner join is used to serve a result which contains only those elements from the first data source that appears only one time in the second data source. And if an element of the first data source does not have matching elements, then it will not appear in the result data set.

How do you write a join in LINQ?

In a LINQ query expression, join operations are performed on object collections. Object collections cannot be "joined" in exactly the same way as two relational tables. In LINQ, explicit join clauses are only required when two source sequences are not tied by any relationship.

Can I join a table to a list using LINQ?

You probably found out that you can't join an Entity Framework LINQ query with a local list of entity objects, because it can't be translated into SQL. I would preselect the database data on the account numbers only and then join in memory.


1 Answers

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.

like image 92
Jon Skeet Avatar answered Sep 19 '22 21:09

Jon Skeet