CSharp examples for System:Math Number
Calculates the median from the given values.
// Copyright (c) Rico Suter. All rights reserved. using System.Linq; using System.Collections.Generic; using System;//from w w w . j a va 2 s. c om public class Main{ /// <summary>Calculates the median from the given values. </summary> /// <param name="values">The values. </param> /// <returns>The median. </returns> public static decimal Median(this IEnumerable<decimal> values) { var sortedList = values.OrderBy(n => n); var count = sortedList.Count(); var itemIndex = count / 2; if (count % 2 == 0) return (sortedList.ElementAt(itemIndex) + sortedList.ElementAt(itemIndex - 1)) / 2; return sortedList.ElementAt(itemIndex); } /// <summary>Calculates the median from the given values. </summary> /// <param name="values">The values. </param> /// <returns>The median. </returns> public static double Median(this IEnumerable<double> values) { var sortedList = values.OrderBy(n => n); var count = sortedList.Count(); var itemIndex = count / 2; if (count % 2 == 0) return (sortedList.ElementAt(itemIndex) + sortedList.ElementAt(itemIndex - 1)) / 2; return sortedList.ElementAt(itemIndex); } }