我使用LinQPad和AdventureWorks LT DB来学习LINQ查询。
我想将下面的SQL转换为LINQ,它是成功的,并得到我想要的。
SELECT SalesOrderID, SUM(OrderQty) as TotalQty, SUM(UnitPrice) as TotalPrice
FROM SalesLT.SalesOrderDetail detail
WHERE detail.SalesOrderID = '71920'
GROUP BY detail.SalesOrderID;
LINQ查询替代上面。
from detail in SalesOrderDetails
where detail.SalesOrderID.Equals(71920)
group detail by detail.SalesOrderID into g
select new {
SalesOrderID = g.Select(item =>item.SalesOrderID).Distinct().First(), /*Distinct() : Enumerable<Int32>, First() Int32 */
TotalQty = g.Select(item =>Convert.ToDouble(item.OrderQty)).Sum(),
TotalPrice = g.Select(item =>item.UnitPrice).Sum()
}
但我知道有必要使用
Select new { ... }
创建另一个struct
?是否可以缩短语法?
感谢。
答案 0 :(得分:4)
在select new
我给你方法语法,但是select部分的内容是相同的。
SalesOrderDetails.Where(sod => sod.SalesOrderID == 71920)
.GroupBy(sod => sod.salesOrderID)
.Select(g => new {
SalesOrderId = g.Key,
TotalQty = g.Sum(i => Convert.ToDouble(i.OrderQty)),
TotalPrice = g.Sum(i => i.UnitPrice)
});
答案 1 :(得分:2)
稍微短一些
from detail in SalesOrderDetails
where detail.SalesOrderID.Equals(71920)
group detail by detail.SalesOrderID into g
select new {
SalesOrderID = g.Key,
TotalQty = g.Sum(item =>Convert.ToDouble(item.OrderQty)),
TotalPrice = g.Sum(item =>item.UnitPrice)
}
Distinct
似乎没必要。另外,如果您指定SalesOrderId
,为什么还要再次选择它?