Home > database >  Is it possible to return integer result from Linq Average method, without casting double result to i
Is it possible to return integer result from Linq Average method, without casting double result to i

Time:09-28

int[] arr = {1,4,5,6,7,2,4,5,6,8,0};

int averageResult = arr.Average(); //?? How to return Average int result. Without casting/convert

In this example, can we obtain int result from Average method, without casting/convert ?

CodePudding user response:

Average() in LINQ returns double so there is no possibility. If you have problem with code cleanliness or you want to shorten code length, then you can do your own extension method that wraps this casting.

public static class ExtensionMethods
{
    public static int AverageInt(this int[] array)
    {
        double avg = array.Average();
        return Math.Round(avg, MidpointRounding.AwayFromZero);
    }
}

and then use it :D

int[] arr = {1,4,5,6,7,2,4,5,6,8,0};

int averageResult = arr.AverageInt();
  • Related