Question

I'm trying to convert the following SQL query to LINQ,

SELECT 
C.CategoryId
, CategoryName 
,COUNT(DISTINCT I.ItemId)
FROM 
Categories  C
    LEFT JOIN  Items I
        ON I.CategoryId = C.CategoryId AND I.SubCategoryId = 1
GROUP BY C.CategoryId, C.CategoryName

Need all the categories even if the item count is 0.

Was it helpful?

Solution

Using a group join, it should look something like this...

var result = Categories
                 .GroupJoin(
                     Items.Where(i => i.SubCategoryId == 1),
                     c => c.CategoryId, 
                     i => i.CategoryId,
                     (c, i) => new { c.CategoryId, c.CategoryName, i.Count() })
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top