get median from a list of number with Linq code example
Example: c# odd even median
public static void Main(string[] args)
{
int[] a = { 1, 4, 5, 8, 19, 12, 15 };
List<int> l = new List<int>(a); l.Sort();
List<int> even = new List<int>();
List<int> odd = new List<int>();
int medianOdd;
int medianEven;
foreach (int num in l)
{
if (num % 2 == 0) even.Add(num);
else odd.Add(num);
}
if (even.Count % 2 != 0) medianEven = even[even.Count / 2];
else medianEven = (even[(even.Count - 1) / 2] + even[even.Count / 2]) / 2;
if (odd.Count % 2 != 0) medianOdd = odd[odd.Count / 2];
else medianOdd = (odd[(odd.Count - 1) / 2] + odd[odd.Count / 2]) / 2;
Console.Write($"Even Median = {medianEven} Odd Median = {medianOdd}");
}