Click here to Skip to main content
Rate this: bad
good
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 OR IEnumerator
Posted 17-Jan-13 3:52am
Tejal S1.9K
Comments
Sergey Alexandrovich Kryukov at 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 at 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
0 OriginalGriff 7,205
1 DamithSL 5,114
2 Maciej Los 4,866
3 Sergey Alexandrovich Kryukov 4,747
4 Kornfeld Eliyahu Peter 4,474


Advertise | Privacy | Mobile
Web04 | 2.8.141223.1 | Last Updated 17 Jan 2013
Copyright © CodeProject, 1999-2014
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