Subquery in LINQ that's in the select statement, not the where clause

南笙酒味 提交于 2019-12-22 06:32:51

问题


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.


回答1:


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);
}


来源:https://stackoverflow.com/questions/2098375/subquery-in-linq-thats-in-the-select-statement-not-the-where-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!