.net - 将两个 LINQ 查询合并为一个

标签 .net linq entity-framework linq-to-entities

我有一个表,其中大约有 15 个不同的字段,其中一些是 JobID(整数字段)、Cost(整数字段)和 LastUpdated(日期时间字段)

JobID  Cost      LastUpdated
 1      10        10-July-2011
 1      15        11-June-2011
 2      25        5-May-2011
 1      15        12-April-2011

Is it possible to write one LINQ query to get the sum of Cost for job id = 1 and also the last date such a cost incurred?

The example query output for the sample data above to look like this below:

40 , 10-july-2011

Currently I am doing it with two different linq queries like this, resulting in two hits to the database from the website in this particular case.

//for last updated
(from row in MyTable where row.JobID == 1
 orderby row.LastUpdated descending
 select row.LastUpdated).First()

//for sum of cost
(from row in MyTable  
 where row.JobID == 1
 select row.Cost).Sum()

在这种情况下,一个 linq 查询会更好吗?在整个页面加载过程中类似的情况将导致对数据库的多次命中,总共大约 18 次,针对 9 个不同的表。在将总和和 LastUpdated 日期合并到一个查询中时,我试图将命中计数减少到 9,每个表一个。

感谢您的宝贵时间...

最佳答案

是的,你可以像这样groupby

var query = from row in MyTable
            group row by row.JobID into rows
            where rows.Key == 1 
            select new
            {
              LastUpdated = rows.Select(x => x.LastUpdated).OrderByDescending(x => x).First(),
              Cost = rows.Sum(x => x.Cost),
            };

关于.net - 将两个 LINQ 查询合并为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9804827/

相关文章:

c# - 如何使用反射在运行时构建此 c# "Expression"?

c# - 在 .NET 中使用整数填充列表的更简单方法

c# - 将两个 List<T> 组合在一起,使用 LINQ 根据实例成员合并 T 的实例

c# - 如何将包含逗号分隔字符串值的字典转换为键值对集合?

asp.net - 如何使用另一个表中的列来引用两个表 - Entity Framework

javascript - 在同一页面上出现两次的用户控件需要 JavaScript 的唯一 div id

c# - 如何找到未使用 PrincipalSearcher 设置属性的 UserPrincipal?

c# - 是否建议在 Windows 服务中运行 Visual Studio Tools for Office?

visual-studio-2010 - Entity Framework 加入 ms-access

c# - 尝试使用 MySQL Entity Framework 6 运行控制台应用程序时出现 ConfigurationErrorException