Linq Group&和

时间:2011-02-16 08:49:02

标签: c# linq

我真的以为我现在正在使用linq,我有一对多关系,我需要返回Jobitems的SUM(jobitems.Cost)

List<Models.Inventory.JobItem> jobItems = BLL.Inventory.JobItem.GetAllActive(forceReload);
List<.Models.Inventory.Job> jobs = BLL.Inventory.Job.GetAllActive(forceReload);
    var getInvoicedItems2 = from j in jobs
    join ji in jobItems on j.JobId equals ji.JobId
    select new { JobCost = ji.Cost, JobId = ji.JobId};

我已经走到了这一步但我不确定如何通过ji.JobId

分组

2 个答案:

答案 0 :(得分:3)

您可以使用群组联接将所有作业项目分组到一个集合中,然后获取该集合中所有成本的总和。

var jobItems = BLL.Inventory.JobItem.GetAllActive(forceReload);
var jobs = BLL.Inventory.Job.GetAllActive(forceReload);
var query = from j in jobs
            join ji in JobItems on j.JobId equals ji.JobId into items
            select new
            {
                JobId = j.JobId,
                JobCost = items.Sum(ji => ji.Cost),
            };

答案 1 :(得分:0)

var getInvoicedItems2 = from ji in jobItems
    group ji by ji.JobId
    into g
    select new {JobId = g.Key, Cost = g.Sum(p => p.Cost)};

var getInvoicedItems = from j in jobs
    from s in schedules
    from i in invoices
    from jj in getInvoicedItems2
    where i.JobId == j.JobId && j.ScheduleId == s.ScheduleId && jj.JobId == j.JobId
    select new { JobCost = jj.Cost, InvoiceDate = i.CreatedDate, Status = i.Status, };

似乎工作