优化C#lambda查询以访问linq查询中的第二个相关字段

时间:2018-01-14 04:58:47

标签: c# linq lambda

好的......在这方面取得了很好的进展,但需要比现在更进一步。

我有两个相关的表格billing_transactionsbilling_transaction_accessorial_charge。第二个是第一个的许多。

第二个表有一个类型和一个电荷,我需要在我的查询中知道它是否有,一个或两个以及收费金额是多少。

service_code_id

的类型
1 (meaning this delivery is a residential delivery) 

2 (meaning it has a dish machine) 

交货可以同时具备。其费用存储在一个名为charge的字段中。

我目前有这个:

var gridData = (from d in db.billing_transactions
                where (d.Id > 954 && d.Id < 958)
                select new
                            {
                                d.base_amount,
                                d.Id,
                                dishmachine = d.billing_transaction_accessorial_charge.Where
                                    (p => p.service_code_id == 2),
                                residential = d.billing_transaction_accessorial_charge.Where
                                    (p => p.service_code_id == 1),
                            }
                ).ToArray();

这会返回有多少洗衣机或剩余电量的计数,但我无法弄清楚如何获得第二个字段。

子表的数据库结构是:

id 
service_code_id 
billing_transaction_id
amount

有人有什么想法吗?

编辑:这是最终的代码块:

 var gridData = (from d in db.billing_transactions
                        where (d.Id > 954 && d.Id < 958)
                        select new
                        {
                            d.base_amount,
                            d.Id,
                            dish_charge = d.billing_transaction_accessorial_charge.Where 
                            (p =>   p.service_code_id == 2)
                            .Sum(l => l.amount),
                            dish_count = d.billing_transaction_accessorial_charge.Where
                            (p => p.service_code_id == 2),
                            res_count = d.billing_transaction_accessorial_charge.Where
                            (p => p.service_code_id == 1),
                            res_charge = d.billing_transaction_accessorial_charge.Where
                            (p => p.service_code_id == 1)
                            .Sum(l => l.amount),
                        }
                      ).ToArray();

1 个答案:

答案 0 :(得分:0)

这将是Sum amount,如果这是您想要的

var gridData = (from d in db.billing_transactions
                where (d.Id > 954 && d.Id < 958)
                select new
                            {
                                d.base_amount,
                                d.Id,
                                dishmachine = d.billing_transaction_accessorial_charge
                                                .Where(p => p.service_code_id == 2)
                                                .Sum(x => x.amount),
                                residential = d.billing_transaction_accessorial_charge
                                                .Where(p => p.service_code_id == 1)
                                                .Sum(x => x.amount),
                            }).ToArray();