Home > Blockchain >  Adding a sum to a list instead of a count
Adding a sum to a list instead of a count

Time:07-01

I'm using ASP.Net Core 3.1 to develop a web app. We need to return a list of values to a View. The list includes counts and sums of data. We have created a ViewModel to help. It looks like this:

public class ObjectCountViewModel
{
    [DisplayName("Description")]
    public string Description { get; set; }

    [DisplayName("Count")]
    public decimal Count { get; set; }

}

We created a list in the Controller to return the values. It looks like this:

  List<ObjectCountViewModel> objectCounts = new List<ObjectCountViewModel>();

Next we added values to the list like this:

int itemsToCount = objects.Where(e => e.ObjectItems.Where(ep => ep.ObjectItemType.Description.Contains("ItemToCount") && ep.ObjectItemSelctionType.Description.Contains("Taken")).Count()>0).Count();
            
objectCounts.Add(new ObjectCountViewModel() { Description = "Items Counted", Count = itemsToCount });

This code works great! But we also need to generate a sum. this will be used to count items with a decimal I can't get a sum to work. Here is one of the solutions I have tried:

decimal itemToSum = objects.Where(e => e.ObjectItems.Where(ep => ep.ObjectItemType.Description.Contains("ItemToSum") && ep.ObjectItemSelectionType.Description.Contains("Taken") && ep.ObjectValueAmount>0).Sum()>0).Sum();
            
objectCounts.Add(new ObjectCountViewModel() { Description = "Items Taken Sum", Count = itemToSum });

I have received a wide variety of errors. The current one is: 'IEnumerable' does not contain a definition for 'Sum' and the best extension method overload 'ParallelEnumerable.Sum(ParallelQuery)' requires a receiver type of 'ParallelQuery,decimal>.

What am I doing wrong? What should my query look like for a sum?

CodePudding user response:

If you have a list of lists, where you want to count all lists, then use listsOfList.SelectMany(x=>x).Count().

If you have a list of decimals, where you want a sum of all decimals, then use listsOfDecimals.Sum().

If you have a list of lists of decimals, where you want a sum of all decimals, then use listsOfListOfDecimals.SelectMany(x=>x).Sum().

CodePudding user response:

I found the answer thanks to Heretic Monkey and Intellisense. I had to create a new object with the value I'm trying to sum and then filter to only select from ones that met my criteria. Then, I separated the Select statement from the Where Clause as Heretic Monkey said. Intellisense suggested I put (decimal) in front of the whole thing, and it worked! Here is my final code for this problem.

decimal itemToSum = (decimal)Objects.Where(ep => ep.RelatedObjectType.Description.Contains("Description") && ep.DifferentRelatedObjectType.Description.Contains("Description")).Select(ep => ep.itemToSum).Sum();
  • Related