Click here to Skip to main content
13,096,858 members (79,297 online)
Rate this:
Please Sign up or sign in to vote.
See more:
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<t> OR IEnumerator<t>
Posted 17-Jan-13 2:52am
Sergey Alexandrovich Kryukov 17-Jan-13 12:00pm
What prevents you from just reading on this interface? Everything is explained in MSDN...

1 solution

Rate this: bad
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();
    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;
        // count is odd, return the middle element
        return temp[count / 2];
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 |
Web04 | 2.8.170813.1 | Last Updated 17 Jan 2013
Copyright © CodeProject, 1999-2017
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