LINQ Interview Question #129

How does Average work in LINQ?

Advanced LINQ, Practical Problems & Senior Interview Scenarios Senior Advanced

Quick Interview Answer

Average calculates the arithmetic mean of a numeric sequence or numeric projection. Its return type depends on the source numeric type and nullable behavior.

Detailed Explanation

Average calculates the arithmetic mean of a numeric sequence or numeric projection. Its return type depends on the source numeric type and nullable behavior.

For an empty non-nullable sequence, Average throws InvalidOperationException. When working with database providers, Average is normally translated to the provider's corresponding aggregate operation when supported.

Code Example

double averageScore = scores.Average();

decimal averagePrice =
    products.Average(p => p.Price);