The subquery in LINQ that is in the select clause, not the where clause

I need to do something like the following

SELECT p.name, 
   (SELECT COUNT(p.id) FROM products WHERE products.parent_id = p.id) AS sub_products
FROM products AS p

I see many LINQ examples of subqueries in the where clause, but nothing like where it is in the select statement.

+5
source share
1 answer

This query should be equivalent:

var query = Products.Select(p => new {
                         p.Name,
                         SubProducts = Products.Count(c => c.parent_id == p.id)
                     });

foreach (var item in query)
{
    Console.WriteLine("{0} : {1}", item.Name, item.SubProducts);
}
+3
source

All Articles