[英]What is the LINQ/Lambda equivalent to Select Count(*), SUM(someColumn) From SomeTable
[英]LINQ Equivalent of "select *, count()"
我在 SQL 服務器上有兩個表 A、B,如下所示:
A 的列:id1、id2、col_1、...、col_100
B 的列:id1、id2、...(某些列)
我想在 C# Linq 中寫下 SQL 查詢的等價物:
select *, (select count(*) from B where A.id1 = B.id1 and A.id2 = b.id2) from A
我知道這可以像下面這樣完成:
var lst = db.TableA.Select(a => new {
id1 = a.id1,
id2 = a.id2,
col_1 = a.col_1,
...
,
col_100 = a.col_100,
count = db.TableB.Where(b => b.id1 = a.id1 && b.id2 == a.id2).Count()
});
但是在這種格式中,我必須提到表 A 的所有列,而我只想在表 A 的現有列中添加一個新列,如下所示: select *, count()
你能幫助我嗎?
這個怎么樣:
var result = dbContext.TableA.Select(a => new
{
A = a,
Count = dbContext.TableB.Where(b => b.id1 = a.id1 && b.id2 == a.id2)
.Count(),
});
因此,您將 select 屬性 A 中 tableA 的完整行,並將 tableB 中相應項目的數量放入屬性 Count
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.