非常直接,我正在尝试Sum
Amount + Adjusted
我确定它不是最好的使用方法。
var a1 = context.Employee.Select( a => a.Amount).ToList().Sum();
var b1 = context.Employee.Select(b => b.Adjusted).ToList().Sum();
var c1 = a1+b1;
答案 0 :(得分:4)
无需创建任何列表(如果这是LINQ to SQL或EF,则会从数据库中提取大量数据) - 您可以使用:
var c1 = context.Employee.Sum(x => x.Amount + x.Adjusted);
假设您不需要个人总和。如果你这样做,我可能会使用:
var a1 = context.Employee.Sum(x => x.Amount);
var b1 = context.Employee.Sum(x => x.Adjusted);
var c1 = a1 + b1;
诚然,这是两个电话。这个可以完成Aggregate
,但肯定会更加丑陋。
var both = context.Employee.Aggregate(
new { Amount = 0, Adjusted = 0 }, // Seed
(pair, emp) => new { pair.Amount + emp.Amount,
pair.Adjusted + emp.Adjusted });
var a1 = both.Amount;
var b1 = both.Adjusted;
var c1 = a1 + b1;
答案 1 :(得分:1)
除了@Jon Skeet的帖子,还有一些与主题相关的调查。
此处ID
的{{1}} int
和CustomerID
<{1}}
int?
将被翻译为:
Purchases.Sum(p => p.ID + p.CustomerID);
和
SELECT
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
SUM([Extent1].[A1]) AS [A1]
FROM ( SELECT
[Extent1].[ID] + [Extent1].[CustomerID] AS [A1]
FROM [dbo].[Purchase] AS [Extent1]
) AS [Extent1]
) AS [GroupBy1]
将被翻译为:
Purchases.Sum(p => p.ID + (p.CustomerID ?? 0));