Skip to content

Instantly share code, notes, and snippets.

@arielsrv
Created September 10, 2022 10:27
Show Gist options
  • Save arielsrv/372e8029fcc2315d32a38260ac388a0e to your computer and use it in GitHub Desktop.
Save arielsrv/372e8029fcc2315d32a38260ac388a0e to your computer and use it in GitHub Desktop.
dotnet 6 test
namespace MyExtensions.Test;
public static class IEnumerableExtensions
{
public static double Median(this IEnumerable<double>? source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
List<double> elements = source.OrderBy(x => x).ToList();
if (!elements.Any()) throw new InvalidOperationException();
int count = elements.Count;
if (count % 2 != 0) return elements[count / 2];
return (elements[count / 2 - 1] + elements[count / 2]) / 2;
}
}
public class IEnumerableExtensionsTest
{
[Fact]
public void Get_Even_Median()
{
List<double> values = new() { 1, 2 };
double actual = values.Median();
Assert.Equal(1.5, actual);
}
[Fact]
public void Get_Odd_Median()
{
List<double> values = new() { 1, 2, 3 };
double actual = values.Median();
Assert.Equal(2, actual);
}
[Fact]
public void Get_Null_Median()
{
ArgumentException e = Assert.Throws<ArgumentNullException>(() => IEnumerableExtensions.Median(null));
Assert.Equal("Value cannot be null. (Parameter 'source')", e.Message);
}
[Fact]
public void Get_Empty_Median()
{
Assert.Throws<InvalidOperationException>(() => new List<double>().Median());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment