public void TestComparerEquality() { Func <int, int> f = i => - i; TestEquality(Comparers.Create(f), Comparers.Create(f), Comparers.Create((int i) => i.ToString())); TestEquality(Comparers.Reverse <int>(), Comparers.Reverse <int>(), Comparers.Create((int i) => i.ToString()).Reverse()); var first = Comparers.Create((string s) => s.Length); var second = Comparers.Create((string s) => s[0]); TestEquality(first.ThenBy(second), first.ThenBy(second), second.ThenBy(first)); TestEquality(Comparers.GetSequenceComparer <string>(), Comparers.GetSequenceComparer(Comparer <string> .Default), Comparers.GetSequenceComparer(StringComparer.OrdinalIgnoreCase)); }
public void TestReverse() { Enumerable.Range(0, 5).OrderBy(i => i, Comparers.Reverse <int>()) .SequenceShouldEqual(new[] { 4, 3, 2, 1, 0 }); Assert.Same(Comparers.Reverse <int>(), Comparers.Reverse <int>()); Assert.Same(Comparers.Reverse <int>(), Comparer <int> .Default.Reverse()); var backwardsStringComparer = Comparer <string> .Create((s1, s2) => string.CompareOrdinal(string.Join(string.Empty, s1.Reverse()), string.Join(string.Empty, s2.Reverse()))); var reverseBackwardsStringComparer = backwardsStringComparer.Reverse(); new[] { "abc", "cab", "bac" }.OrderBy(s => s, reverseBackwardsStringComparer) .SequenceShouldEqual(new[] { "abc", "bac", "cab" }); Assert.Throws <ArgumentNullException>(() => reverseBackwardsStringComparer.Compare("a", null)); Math.Sign(Comparer <int?> .Default.Reverse().Compare(1, null)).ShouldEqual(-1); }
public void TestMinByAndMaxBy() { Assert.Throws <ArgumentNullException>(() => default(IEnumerable <object>).MinBy(x => 2)); Assert.Throws <ArgumentNullException>(() => default(IEnumerable <object>).MaxBy(x => 2)); Assert.Throws <ArgumentNullException>(() => new[] { 1 }.MinBy(default(Func <int, int>))); Assert.Throws <ArgumentNullException>(() => new[] { 1 }.MaxBy(default(Func <int, int>))); Assert.Throws <InvalidOperationException>(() => new int[0].MinBy(i => "a")); Assert.Throws <InvalidOperationException>(() => new int[0].MaxBy(i => "a")); new int?[0].MinBy(i => "a").ShouldEqual(null); new int?[0].MaxBy(i => "a").ShouldEqual(null); new string[0].MinBy(i => 1).ShouldEqual(null); new string[0].MaxBy(i => 1).ShouldEqual(null); new[] { "z", "aa", }.MinBy(s => s.Length).ShouldEqual("z"); new[] { "z", "aa" }.MaxBy(s => s.Length).ShouldEqual("aa"); new[] { default(int?), 1, default(int?) }.MinBy(i => i).ShouldEqual(1); new[] { default(int?), 1, default(int?) }.MaxBy(i => i).ShouldEqual(1); new[] { 1, 2, 3, 2, 1 }.MinBy(i => 2 * i, Comparers.Reverse <int>()).ShouldEqual(3); new[] { 3, 2, 1, 2, 3 }.MaxBy(i => 2 * i, Comparers.Reverse <int>()).ShouldEqual(1); }