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 ?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With