Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subquery in LINQ that's in the select statement, 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 lots of LINQ examples of subqueries in the where clause,but nothing like this where it's in the select statement.

like image 950
Jhorra Avatar asked Jan 20 '10 01:01

Jhorra


1 Answers

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);
}
like image 132
Ahmad Mageed Avatar answered Oct 13 '22 00:10

Ahmad Mageed