Skip to main content
 首页 » 编程设计

c#之linq group by with join

2024年02月23日15落叶

[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引用同一个表 我的问题是如何编写 linq2Sql 查询来检索以下结果:

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

换句话说,我想检索几乎没有 id 但与第二个表中的计数分组的第一个表

请您参考如下方法:

像这样:

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