我有一个表,其中大约有 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,每个表一个。
感谢您的宝贵时间...
最佳答案
是的,你可以像这样group
by
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/