Search This Blog

Thursday, April 23, 2015

LINQ Average excluding or including zeros c#

C# > LINQ > Average


Average computes the average of a sequence of numeric values.

Example


int[] int_array = new int[] { 5, 4, 2, 8, 10, 0 };

// linq average excluding zeros

double avg =
       (from ord in int_array
        where ord > 0
        select ord).Average();  // 5.8

// linq average including zeros 
avg =
       (from ord in int_array
       select ord).Average();    // 4.83