linq group by with join

时间:2011-05-29 18:59:07

标签: c# linq linq-to-sql join group-by

[Firstid foreignId field]
[1       1         textFirst1]
[2       1         textFirst2]
[3       1         textFirst3]
[4       2         textFirst4]
[5       2         textFirst5]

[Secondid foreignId field]
[1        1         textSec1]
[2        1         textSec2]
[3        2         textSec3]

foreignId reffer到同一个表 我的问题是如何编写linq2Sql查询以检索以下结果:

[foreignId countFromSecond fieldFromFirst]
[1         2               textFirst1]
[1         2               textFirst2]
[1         2               textFirst3]
[2         1               textFirst4]
[2         1               textFirst5]

换句话说,我想要几乎没有id的第一个表,但是从第二个表

计算了gruoped

1 个答案:

答案 0 :(得分:4)

这样的事情:

var query =
    from first in db.FirstTable
    select
        new
        {
            first.foreignId,
            countFromSecond = db.SecondTable
                .Where(arg => arg.foreignId == first.foreignId)
                .Count(),
            first.fieldFromFirst
        };