Wednesday, January 26, 2011

Use LINQ To Get The SUM Or Total Of A Property Value On An Object Collection

If you have an object collection say List(Of <T>) and you want to add up all of the values of a single property of the proper type (Integer, Double, etc.), you can do this using LINQ and a lambda expression. We will use the SUM LINQ Extension Method directly on the collection that implements IEnumerable(T), and provide it an anonymous function that takes the property value to be added together. So here is the code using an object collection which I had already populated previously:

'Use the LINQ SUM Extension Method to iterate over the collection and extract the total.
Dim Total = MyDataCollection.Sum(Function(x) x.PropertyOnXToSumTogether)
The anonymous function takes a parameter which will represent the individual instance of the collection, and then uses the property designated to be iterated over and added to the total.

No comments:

Post a Comment