MSDN上的LINQ to SQL示例页给出了如何完成此操作的示例。LINQ to Objects的代码应该与之非常相同。 这里的关键是调用DefaultIfEmpty。
Dim q = From e In db.Employees _
Group Join o In db.Orders On e Equals o.Employee Into ords = Group _
From o In ords.DefaultIfEmpty _
Select New With {e.FirstName, e.LastName, .Order = o}
var teams = new[]
{
new { Id = 1, Name = "Tigers" },
new { Id = 2, Name = "Sharks" },
new { Id = 3, Name = "Rangers" },
};
var players = new[]
{
new { Name = "Abe", TeamId = 2},
new { Name = "Beth", TeamId = 4},
new { Name = "Chaz", TeamId = 1},
new { Name = "Dee", TeamId = 2},
};
// SelectMany generally aggregates a collection based upon a selector: from the outer item to
// a collection of the inner item. Adding .DefaultIfEmpty ensures that every outer item
// will map to something, even null. This circumstance makes the query a left outer join.
// Here we use a form of SelectMany with a second selector parameter that performs an
// an additional transformation from the (outer,inner) pair to an arbitrary value (an
// an anonymous type in this case.)
var teamAndPlayer = teams.SelectMany(
team =>
players
.Where(player => player.TeamId == team.Id)
.DefaultIfEmpty(),
(team, player) => new
{
Team = team.Name,
Player = player != null ? player.Name : null
});
teamAndPlayer.Dump();
// teamAndPlayer is:
// {
// {"Tigers", "Chaz"},
// {"Sharks", "Abe"},
// {"Sharks", "Dee"},
// {"Rangers", null}
// }
public static class extends
{
public static IEnumerable<T> LefJoinBNull<T, TKey>(this IEnumerable<T> source, IEnumerable<T> Target, Func<T, TKey> key)
{
if (source == null)
throw new ArgumentException("source is null");
return from s in source
join j in Target on key.Invoke(s) equals key.Invoke(j) into gg
from i in gg.DefaultIfEmpty()
where i == null
select s;
}
}
5条答案
按热度按时间uqcuzwp81#
MSDN上的LINQ to SQL示例页给出了如何完成此操作的示例。LINQ to Objects的代码应该与之非常相同。
这里的关键是调用
DefaultIfEmpty
。如果您需要将其转换为C#的帮助,请询问。
vcudknz32#
这是LINQ中的example of a left join。
72qzrwbm3#
例如:
将从www.example.com成员资格中为您提供一个角色列表asp.net,如果与指定用户(iduser关键字)不匹配,则为空
c0vxltue4#
我发现我喜欢的方法是将
OuterCollection.SelectMany()
与InnerCollection.DefaultIfEmpty()
结合起来。您可以使用“C#语句”模式在LINQPad中运行以下代码。在进行试验时,我发现有时可以在匿名类型的示例化中省略
player
的空值检查。(代替这里的这些数组,我认为这使它成为LINQ-to-objects(对象链接)之类的东西。)我认为省略null检查在LINQ-to-SQL,因为查询被转换为SQLx 1 m3n1x,它直接跳到将null与外部项连接起来。(注意,匿名对象的属性值必须是nullable;因此,如果您希望安全地包含一个int
,那么您需要类似于以下内容:new { TeamId = (int?)player.TeamId }
.imzjd6km5#
我试着重现著名的左连接,其中B键为空,得到的结果是这个扩展方法(只要有一点想象力,你就可以修改它,只做一个左连接):