Average is a LINQ functionality which calculates average value of given collection. It works with both collections of primitive values and complex objects. Below article provides example of each one.
List of integers
Average value can be calculated by calling Average function.
In case of collection having null values, such items are being ignored when calculating average. As it is presented on below example, there are two additional null elements, but result is still 3.
List of objects
It is possible to calculate average value of selected property of given objects collection. For such purpose let’s use example Fruit class. It contains Price property, which we’ll use to get average figure.
We also need some sample list of Fruit objects.
Finally, we can call Average to get the result. This time it requires an argument which is a selector of an object against which average will be calculated. In our case it is Price property.
Need Help with Your C# Projects?
We offer expert support and development services for projects of any size. Contact us for a free consultation and see how we can help you succeed.
CONTACT US NOW