Linq查询中的链接连接(?)

时间:2013-03-15 16:53:31

标签: c# linq entity-framework

我很难相信我这么长时间一直在使用Linq并且无法解决这个问题......我以前必须这样做,但是我的大脑让我失望了。

我想要做的主要是

from a in A
join b in B on a.aId equals b.aId into Bees
join c in C on b.bId equals c.bId into Cees
select new { a.id, Bees, Cees }

可以这样做,如果是这样的话怎么办?我得到“无法解析符号b”,如果我在c连接条件下将b更改为Bees,当然这是一个集合,所以我无法加入id ...

2 个答案:

答案 0 :(得分:4)

from a in A
join b in B
on a.aId equals b.aId into Bees
from bs in Bees
join c in C 
on bs.bId equals c.bId into Cees
select new { a.Id, Bees, Cees };

类定义

class AA
{
    public int Id { get; set; }
    public int aId { get; set; }
}

class BB
{
    public int Id { get; set; }
    public int aId { get; set; }
    public int bId { get; set; }
}

class CC
{
    public int Id { get; set; }
    public int bId { get; set; }
}

主程序

class Program
{
    static void Main(string[] args)
    {
        var A = new List<AA>();
        var B = new List<BB>();
        var C = new List<CC>();

        // make up some data
        var bid = 1;
        var cid = 1;
        for (var a = 1; a < 4; a++)
        {
            A.Add(new AA { Id = a, aId = a });

            for (var b = 1; b < 4; b++)
            {
                B.Add(new BB { Id = bid++, aId = a, bId = b });

                for (var c = 1; c < 4; c++)
                    C.Add(new CC { Id = cid++, bId = b });
            }
        }

        // display the item count for each list
        Console.WriteLine("A: {0}", A.Count());
        Console.WriteLine("B: {0}", B.Count());
        Console.WriteLine("C: {0}", C.Count());

        // define the query
        var abc = from a in A
                  join b in B
                  on a.aId equals b.aId into Bees
                  from bs in Bees
                  join c in C 
                  on bs.bId equals c.bId into Cees
                  select new { a.Id, Bees, Cees };

        // display the results of the query in the console
        foreach (var x in abc)
        {
            var bees = x.Bees.Count();
            var cees = x.Cees.Count();
            var str = String.Format("Id: {0}, Bees: {1}, Cees: {2} ", x.Id, bees, cees);
            Console.WriteLine(str);
        }
     }
}

输出

A: 3
B: 9
C: 27

Id: 1, Bees: 3, Cees: 9
Id: 1, Bees: 3, Cees: 9
Id: 1, Bees: 3, Cees: 9
Id: 2, Bees: 3, Cees: 9
Id: 2, Bees: 3, Cees: 9
Id: 2, Bees: 3, Cees: 9
Id: 3, Bees: 3, Cees: 9
Id: 3, Bees: 3, Cees: 9
Id: 3, Bees: 3, Cees: 9

答案 1 :(得分:1)

请注意,当您到达join cb时,它不存在,因为它位于集合Bees中。由于您加入了其他ID,除了a中的ID之外,还不只有一个ID可以加入。对于每个蜜蜂集合,您需要为c 加入b

from a in A
join b in B on a.aId equals  b.aId into Bees
select new { a.id, Bees, 
    Cees = from b in Bees 
    join c in C on b.bId equals c.bId
    select v}

如果没有进行群组加入,而是进行常规加入,那会更有意义:

from a in A
join b in B on a.aId equals b.aId
join c in C on b.bId equals c.bId
select new { a.id, b, c}

现在不知道问题的背景,很难说这是否有助于解决你的问题。