Hoàng Đỗ Huy
Hoàng Đỗ Huy

Reputation: 79

Calculate sum of child entities of list parent enities

I have to calculate the total fee of services that have child services. The way to calculate sum of Entities in linq is:

double totalcost = db.Services.Sum(s=>s.cost);

But how could i calculate to total fee of list services such as:

double totalfee=db.services.childservices.sum(s=>s.fee);

or something like that? I dont want to use loop as while cause it's take a long time when i have to calculate 1000 services at a time!

Upvotes: 3

Views: 1966

Answers (3)

ycsun
ycsun

Reputation: 1855

I suppose your model is something like the following:

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 over all services:

double? totalFee = db.Services.Sum(service => service.ChildServices.Sum(child => (double?)child.Fee));

The double? are there to guard againt the case when there's nothing to sum in the database. In that case the result will be null.

If you want a list of total fees over all service, you can:

List<double?> totalFees = db.Services.Select(service => service.ChildServices.Sum(child => (double?)child.Fee)).ToList();

If you want zeros instead of null, just replace the above queries with:

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();

Upvotes: 2

Thirisangu Ramanathan
Thirisangu Ramanathan

Reputation: 614

var childFeeSum=from parentService in db.Services select new { Fee=parentService.Sum(parent=>parent.ChildServices.Sum(f=>f.Fee))};

Upvotes: 0

daryal
daryal

Reputation: 14929

var total = services.SelectMany(q => q.ChildServices).Distinct().Sum(p => p.Fee);

Upvotes: 0

Related Questions