kosnkov
kosnkov

Reputation: 5931

linq group by with join

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

and

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

foreignId reffer to the same table MY question is how to write linq2Sql query to retrive following result:

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

other words, i want to retrive almost first table without id but gruoped with count from second table

Upvotes: 1

Views: 461

Answers (1)

Alex Aza
Alex Aza

Reputation: 78457

Something like this:

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

Upvotes: 4

Related Questions