我的表有大约15个不同的字段,其中一些是JobID(整数字段),Cost(整数字段)和LastUpdated(DateTime字段)
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查询会更好吗?在整个页面加载期间,类似的情况将导致对数据库的多次命中,总共9次访问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),
};