Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum items with certain IDs in IEnumerable of a Custom Class

CustomClass{
int ID;
int numberToSum;
float numToAverage;
}


IEnumerable<CustomClass> results = MethodToPopulateIEnumerable();
List<int> listOfIDs = MethodToGetListOfIDs();

What I wish to do with these, is take my IEnumberable<CustomClass> and select all the ones where the ID is in the List<int> listOfIDs, then I wish to sum the numberToSum value of this and save it in a variable and get the average of the numToAverage property and save it in a variable.

What is the most elegant way to do this ?

like image 422
Simon Kiely Avatar asked Jan 25 '26 12:01

Simon Kiely


1 Answers

I think you are looking for something like this:

IEnumerable<CustomClass> results = MethodToPopulateIEnumerable();
List<int> listOfIDs = MethodToGetListOfIDs();

Query Syntax

 var query = from c in results
             where listOfIds.Any(x => x == c.ID)
             select c;

Method Syntax

var query = results.Where(c => listOfIds.Any(x => x == c.ID));

Calculations

int numberToSum = query.Sum(x => x.numberToSum);
float numToAverage = query.Average(x => x.numToAverage);

Another alternate method which would allievate some of the performances concerns by fellow members, but still allowing the query to be linq-to-whatever friendly (linq-to-entities, linq-to-sql):

var calculations = (from c in results
                   where listOfIds.Any(x => x == c.ID)
                   group c by 1 into g
                   select new {
                     numberToSum = g.Sum(x => x.numberToSum ),
                     numToAverage = g.Average(x => x.numToAverage),                
                   }).FirstOrDefault();
like image 103
Aducci Avatar answered Jan 28 '26 02:01

Aducci