Click here to Skip to main content
12,511,734 members (48,571 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: ASP.NET
There is a web page which displays the median value from a sequence of integer numbers.I neeed to create an extension method to compute the median value.Which interface should I add the extension method to??

Enumerable
Posted 17-Jan-13 2:52am
Comments
Sergey Alexandrovich Kryukov 17-Jan-13 12:00pm
   
What prevents you from just reading on this interface? Everything is explained in MSDN...
—SA

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

If you want to specify an interface as formal parameter type, than IEnumerable. Many thing can be passed to it, like lists or arrays.

Here[^] is a possible implementation:
public static decimal GetMedian(this IEnumerable<int> source)
{
    // Create a copy of the input, and sort the copy
    int[] temp = source.ToArray();
    Array.Sort(temp);
 
    int count = temp.Length;
    if (count == 0)
    {
        throw new InvalidOperationException("Empty collection");
    }
    else if (count % 2 == 0)
    {
        // count is even, average two middle elements
        int a = temp[count / 2 - 1];
        int b = temp[count / 2];
        return (a + b) / 2m;
    }
    else
    {
        // count is odd, return the middle element
        return temp[count / 2];
    }
}
  Permalink  
Comments
Shona22 17-Jan-13 9:02am
   
thnx :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web02 | 2.8.160929.1 | Last Updated 17 Jan 2013
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100