Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to return integer result from Linq Average method, without casting double result to int?

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 ?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
    {
        return (int)array.Average();
    }
}

and then use it 😀

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

int averageResult = arr.AverageInt();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading