Home > OS >  Linq- Finding the Same Record Total
Linq- Finding the Same Record Total

Time:12-22

In the image below, the total number of times which business is viewed each day is kept. What I want to do is to find the total number of views belonging to the same id number. For example, I want to find the total view value of records whose businessId is 400.

Database Table Image

CodePudding user response:

This will do the work, you may need to adapt some stuff indeed :

var totalViewsByBusinessId = records
    .GroupBy(r => r.businessId)
    .Select(g => new
    {
        BusinessId = g.Key,
        TotalViews = g.Sum(r => r.views)
    });

int businessId = 400;
var totalViews = totalViewsByBusinessId
    .FirstOrDefault(g => g.BusinessId == businessId)?.TotalViews ?? 0;

With that, you will get the total amount of views for each business. Then you will just need to use a where to see the total views of the wanted business.

  •  Tags:  
  • linq
  • Related