Calculate the sum of child objects of the parent rights list
I need to calculate the total fee for services that child services have. The way to calculate the sum of Entities in linq:
double totalcost = db.Services.Sum(s=>s.cost);
But how can I calculate the total cost of the list services, for example:
double totalfee=db.services.childservices.sum(s=>s.fee);
or something like that? I don't want to use a loop because it takes a long time when I have to compute 1000 services at a time!
source to share
I assume your model looks something like this:
public class Service
{
public long Id { get; set; }
public double Cost { get; set; }
public ICollection<ChildService> ChildServices { get; set; }
}
public class ChildService
{
public long Id { get; set; }
public double Fee { get; set; }
}
Then you can do this to calculate the total fee for all services:
double? totalFee = db.Services.Sum(service => service.ChildServices.Sum(child => (double?)child.Fee));
double?
there to once again defend the case where nothing is summed up in the database. In this case, the result will be null
.
If you want a list of the general fees for the entire service, you can:
List<double?> totalFees = db.Services.Select(service => service.ChildServices.Sum(child => (double?)child.Fee)).ToList();
If you want zeros instead null
, just replace the above queries:
double totalFee = db.Services.Sum(service => service.ChildServices.Sum(child => (double?)child.Fee)) ?? 0;
List<double> totalFees = db.Services.Select(service => service.ChildServices.Sum(child => (double?)child.Fee) ?? 0).ToList();
source to share