使用LINQ的左联接

rqdpfwrv  于 2022-12-06  发布在  其他
关注(0)|答案(5)|浏览(201)

有人能给予我一个例子,说明如何使用LINQ/lambda表达式执行左连接操作吗?

uqcuzwp8

uqcuzwp81#

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}

如果您需要将其转换为C#的帮助,请询问。

72qzrwbm

72qzrwbm3#

例如:

IQueryable<aspnet_UsersInRole> q = db.aspnet_Roles
                    .Select(p => p.aspnet_UsersInRoles
                        .SingleOrDefault(x => x.UserId == iduser));

将从www.example.com成员资格中为您提供一个角色列表asp.net,如果与指定用户(iduser关键字)不匹配,则为空

c0vxltue

c0vxltue4#

我发现我喜欢的方法是将OuterCollection.SelectMany()InnerCollection.DefaultIfEmpty()结合起来。您可以使用“C#语句”模式在LINQPad中运行以下代码。

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}
//     }

在进行试验时,我发现有时可以在匿名类型的示例化中省略player的空值检查。(代替这里的这些数组,我认为这使它成为LINQ-to-objects(对象链接)之类的东西。)我认为省略null检查在LINQ-to-SQL,因为查询被转换为SQLx 1 m3n1x,它直接跳到将null与外部项连接起来。(注意,匿名对象的属性值必须是nullable;因此,如果您希望安全地包含一个int,那么您需要类似于以下内容:new { TeamId = (int?)player.TeamId } .

imzjd6km

imzjd6km5#

我试着重现著名的左连接,其中B键为空,得到的结果是这个扩展方法(只要有一点想象力,你就可以修改它,只做一个左连接):

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;
    }
}

相关问题