-1

我很难相信我已经使用了这么长时间的 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 ...

4

2 回答 2

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
于 2013-03-15T16:55:21.770 回答
1

请记住,当您到达该join c行时b,它并不存在,因为它在集合中Bees。由于您要使用其他 ID 加入,因此除了 中的 ID 之外a,不只有一个 ID 可以加入。您需要为每个 Bees 集合加入 b 和 c 。

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}

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

于 2013-03-15T17:00:23.380 回答