Could someone give me an example of how to perform a left join operation using LINQ/lambda expressions?
相关问题
- Why wrapping a function into a lambda potentially
- PostgreSQL: left outer join syntax
- Generating powerset in one function, no explicit r
- Check if tie in count of lists using linq
- Trouble with OR in Sharepoint CAML
相关文章
- 想问问Linq中有没有根据条件选择要不要关联表。
- Why doesn't C11 support lambda functions
- Why do I need a ToList() to avoid disposed context
- LINQ .Include() properties from sub-types in TPH i
- Can a method chain be called LINQ?
- Get grouped comma separated values with linq
- How does a LINQ expression know that Where() comes
-
Creating dynamic Expression
>
The LINQ to SQL samples page on MSDN gives an example of how to accomplish this. The code should be pretty much identical for LINQ to Objects.
The key here is the call to
DefaultIfEmpty
.If you need help converting that to C#, just ask.
well i tried to reproduce the famous left join where b key is null and the result i got is this extension method (with a little imagination you can modify it to just make a left join):
For instance:
Will give you a list of roles from the asp.net membership, with nulls where it doesn't match the specified user (iduser key)
Here is an example of a left join in LINQ.
The way I have found that I like is to combine
OuterCollection.SelectMany()
withInnerCollection.DefaultIfEmpty()
. You can run the following in LINQPad using "C# Statements" mode.While experimenting with this, I found that sometimes you can omit the null-check of
player
in the instantiation of the anonymous type. I think that this is the case when using LINQ-to-SQL on a database (instead of these arrays here, which I think makes it LINQ-to-objects or something.) I think that the omission of the null check works in LINQ-to-SQL because the query is translated into a SQLLEFT OUTER JOIN
, which skips straight to joining null with the outer item. (Note that the value of the anonymous object's property must be nullable; so if you want to safely include anint
, say, you would need something like:new { TeamId = (int?)player.TeamId }
.