linq查询连接两个表并从另一个表中获取一个表值的计数

时间:2020-12-21 11:59:52

I have two tables Customers, Orders

我有两个表客户,订单

Customers CustomerID FName LName

客户CustomerID FName LName

Orders OrderId CustomerID OrderDate

订单OrderId CustomerID OrderDate

I want to make a linq statement that can join these two tables and get
FName, LName, Count of orders for each customer

我想创建一个linq语句,可以连接这两个表并获得FName,LName,每个客户的订单数

2 个解决方案

#1


from c in Customers
join o in Orders on c.CustomerID equals o.CustomerID into g
select new { c.FName, c.LName, Count=g.Count() }

#2


from c in db.Customers
let theCount = c.Orders.Count()
select new {c.FName, c.LName, theCount}

http://msdn.microsoft.com/en-us/library/bb425822.aspx#linqtosql_topic11

These access operations translate to more complicated joins or correlated sub-queries in the equivalent SQL, allowing you to walk through your object graph during a query.

这些访问操作转换为等效SQL中更复杂的连接或相关子查询,允许您在查询期间遍历对象图。

#1


from c in Customers
join o in Orders on c.CustomerID equals o.CustomerID into g
select new { c.FName, c.LName, Count=g.Count() }

#2


from c in db.Customers
let theCount = c.Orders.Count()
select new {c.FName, c.LName, theCount}

http://msdn.microsoft.com/en-us/library/bb425822.aspx#linqtosql_topic11

These access operations translate to more complicated joins or correlated sub-queries in the equivalent SQL, allowing you to walk through your object graph during a query.

这些访问操作转换为等效SQL中更复杂的连接或相关子查询,允许您在查询期间遍历对象图。