Exemplo n.º 1
0
        public void CanCreateCanonicalComparer()
        {
            var comparer = ComparerFactory <Product> .Create(
                x => new { x.Name.Length, x.Price },
                (builder, x, y) =>
            {
                builder
                .LessThen(() => x.Length < y.Length || x.Price < y.Price)
                .Equal(() => x.Length == y.Length || x.Price == y.Price)
                .GreaterThan(() => x.Length > y.Length || x.Price > y.Price);
            });

            var products = new[]
            {
                new Product {
                    Name = "Car", Price = 7
                },
                new Product {
                    Name = "Table", Price = 3
                },
                new Product {
                    Name = "Orange", Price = 1
                },
            };

            var sorted = products.OrderByDescending(p => p, comparer).ToList();

            Assert.AreEqual(3, sorted.Count);
            Assert.AreEqual("Orange", sorted.ElementAt(0).Name); // because added first
            Assert.AreEqual("Car", sorted.ElementAt(1).Name);    // because added first
            Assert.AreEqual("Table", sorted.ElementAt(2).Name);  // because ItemCount
        }
Exemplo n.º 2
0
    /// <summary>
    /// Sorts the elements of a sequence in ascending order by using a specified comparison delegate.
    /// </summary>
    public static IOrderedEnumerable <TSource> OrderBy <TSource, TKey>(this IEnumerable <TSource> source, Func <TSource, TKey> keySelector,
                                                                       Func <TKey, TKey, int> comparison)
    {
        var comparer = ComparerFactory <TKey> .Create(comparison);

        return(source.OrderBy(keySelector, comparer));
    }
Exemplo n.º 3
0
        public void TestComparerFactory()
        {
            ComparerFactory f = new ComparerFactory();

            List<TestClass1> list = new List<TestClass1>();
            list.Add(new TestClass1(5, "1"));
            list.Add(new TestClass1(45, "2"));
            list.Add(new TestClass1(40, "233"));

            list.Sort(f.New<TestClass1>("field1"));

            Assert.IsTrue(list[0].field1 == 5);
            Assert.IsTrue(list[1].field1 == 40);
            Assert.IsTrue(list[2].field1 == 45);

            List<TestClass2> list2 = new List<TestClass2>();
            list2.Add(new TestClass2(new TestClass1(5, "3434")));
            list2.Add(new TestClass2(new TestClass1(45, "4")));
            list2.Add(new TestClass2(new TestClass1(10, "342334")));

            list2.Sort(f.New<TestClass2>("class1.field1"));

            Assert.IsTrue(list2[0].class1.field1 == 5);
            Assert.IsTrue(list2[1].class1.field1 == 10);
            Assert.IsTrue(list2[2].class1.field1 == 45);
        }
Exemplo n.º 4
0
        public void TestComparerFactory()
        {
            ComparerFactory f = new ComparerFactory();

            List <TestClass1> list = new List <TestClass1>();

            list.Add(new TestClass1(5, "1"));
            list.Add(new TestClass1(45, "2"));
            list.Add(new TestClass1(40, "233"));

            list.Sort(f.New <TestClass1>("field1"));

            Assert.IsTrue(list[0].field1 == 5);
            Assert.IsTrue(list[1].field1 == 40);
            Assert.IsTrue(list[2].field1 == 45);

            List <TestClass2> list2 = new List <TestClass2>();

            list2.Add(new TestClass2(new TestClass1(5, "3434")));
            list2.Add(new TestClass2(new TestClass1(45, "4")));
            list2.Add(new TestClass2(new TestClass1(10, "342334")));

            list2.Sort(f.New <TestClass2>("class1.field1"));

            Assert.IsTrue(list2[0].class1.field1 == 5);
            Assert.IsTrue(list2[1].class1.field1 == 10);
            Assert.IsTrue(list2[2].class1.field1 == 45);
        }
Exemplo n.º 5
0
        public bool Equal(Object x, Object y, ColumnType type, string tolerance)
        {
            var comparer = new ComparerFactory().Get(type);
            var res      = comparer.Compare(x, y, ToleranceFactory.Instantiate(type, tolerance));

            return(res.AreEqual);
        }
Exemplo n.º 6
0
        internal static ComparsionDelegate <T1, T2> Create(MatchingMemberInfo <T1, T2> mmi, IConfiguration configuration)
        {
            var leftType  = mmi.LeftSideItem.MemberType;
            var rightType = mmi.RightSideItem.MemberType;

            var factory  = new ComparerFactory(configuration);
            var comparer = typeof(ComparerFactory)
                           .GetMethod(nameof(ComparerFactory.Create), BindingFlags.Instance | BindingFlags.NonPublic)
                           ?.MakeGenericMethod(leftType, rightType)
                           .Invoke(factory, null);

            var itemCompareMethodInfo = comparer.GetType().GetMethod("Compare");

            ComparsionResult Func(int level, T1 a, T2 b)
            => CompareFunc(
                mmi.Name,
                configuration.MaxNestingLevel,
                mmi.LeftSideItem.GetValueFunc,
                mmi.RightSideItem.GetValueFunc,
                leftType.Name,
                rightType.Name,
                itemCompareMethodInfo,
                comparer,
                level, a, b);

            return(Func);
        }
Exemplo n.º 7
0
        public void ComparerFromFactory()
        {
            var values   = new int[] { 3, 5, 2, 4, 2, 1 };
            var comparer = ComparerFactory.Create <int>((x, y) => y <= x);

            CollectionAssert.AreEqual(new[] { 5, 4, 3, 2, 2, 1 }, values.OrderBy(x => x, comparer).ToArray());
        }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            var list = new List <int>();

            list.Sort(new ComparerDelegate <int>((x, y) => x - y));   //using without factory

            list.Sort(ComparerFactory.Create <int>((x, y) => x - y)); //using with factory
        }
Exemplo n.º 9
0
 protected virtual IComparer <Item> GetComparer(ID id, Database database, Item item = null)
 {
     if (!this.Comparers.ContainsKey(id))
     {
         this.Comparers[id] = ComparerFactory.GetComparer(item ?? database.GetItem(id));
     }
     return(this.Comparers[id]);
 }
Exemplo n.º 10
0
        private static void MeasureIntPropertyClassComparasions()
        {
            var tuples = GenerateRandomIntPropertyClassPairs();

            var value           = MeasureComparer(new IntPropertyClassEqualityComparer(), tuples);
            var valueReflection = MeasureComparer(ComparerFactory.CreateRecursiveReflectionComparer <IntPropertyClass>(), tuples);

            Console.WriteLine($"{NumberOfCompares} comparasions. Native comparer: {value} miliseconds, " +
                              $"reflection comparer: {valueReflection} miliseconds. ");
        }
Exemplo n.º 11
0
        public void IsSorted_CustomComparerWithNullEnumerable_ViolatesPrecondition()
        {
            // Arrange
            SCG.IEnumerable <int> enumerable = null;
            var comparer = ComparerFactory.CreateComparer <int>((x, y) => x.CompareTo(y));

            // Act & Assert
            // ReSharper disable once ExpressionIsAlwaysNull
            Assert.That(() => enumerable.IsSorted(comparer), Violates.PreconditionSaying(ArgumentMustBeNonNull));
        }
Exemplo n.º 12
0
        public void CreateComparerFromExpression()
        {
            var comparer = ComparerFactory <Person> .Create(x => x.Age);

            comparer.Compare(new Person {
                Age = 1
            }, new Person {
                Age = 1
            })
            .Should().Be(0);
        }
Exemplo n.º 13
0
        public void IsSorted_CustomComparer_IsNotSorted(int[] array)
        {
            // Arrange
            var comparer = ComparerFactory.CreateComparer <int>((x, y) => x.CompareTo(y));

            // Act
            var isSorted = array.IsSorted(comparer);

            // Assert
            Assert.That(isSorted, Is.False);
        }
Exemplo n.º 14
0
        public void UnsequenceEqual_CustomComparerNotEquals_False(int[] first, int[] second)
        {
            // Arrange
            var comparer = ComparerFactory.CreateEqualityComparer((x, y) => x == y, (int x) => x.GetHashCode());

            // Act
            var result = first.UnsequenceEqual(second, comparer);

            // Assert
            Assert.That(result, Is.False);
        }
Exemplo n.º 15
0
        public void IsSorted_ReversedComparer_IsSortedInReverse(int[] array)
        {
            // Arrange
            var comparer = ComparerFactory.CreateComparer <int>((x, y) => y.CompareTo(x));

            // Act
            var isSorted = array.IsSorted(comparer);

            // Assert
            Assert.That(isSorted, Is.True);
        }
Exemplo n.º 16
0
        public void EqualityComparer_CustomEqualityComparer_Equal()
        {
            // Arrange
            var customEqualityComparer = ComparerFactory.CreateEqualityComparer <int>((i, j) => i == j, i => i);
            var collection             = GetEmptyExtensible(customEqualityComparer);

            // Act
            var equalityComparer = collection.EqualityComparer;

            // Assert
            Assert.That(equalityComparer, Is.SameAs(customEqualityComparer));
        }
Exemplo n.º 17
0
        public void Constructor_EqualityComparer_EqualsGivenEqualityComparer()
        {
            // Arrange
            var customEqualityComparer = ComparerFactory.CreateEqualityComparer <int>((i, j) => i == j, i => i);

            // Act
            var list             = new ArrayList <int>(equalityComparer: customEqualityComparer);
            var equalityComparer = list.EqualityComparer;

            // Assert
            Assert.That(equalityComparer, Is.SameAs(customEqualityComparer));
        }
Exemplo n.º 18
0
        // Fast for array lists and similar, but not stable; slow for linked lists

        public static ArrayList <int> GetPermutation1 <T>(IList <T> lst)
            where T : IComparable <T>
        {
            ArrayList <int> res = new ArrayList <int>(lst.Count);

            for (int i = 0; i < lst.Count; i++)
            {
                res.Add(i);
            }
            res.Sort(ComparerFactory <int> .CreateComparer((i, j) => lst[i].CompareTo(lst[j])));
            return(res);
        }
Exemplo n.º 19
0
 private static SCG.IEqualityComparer <T> GetIdenticalityComparer <T>()
 {
     if (!typeof(T).IsValueType)
     {
         return(ComparerFactory.CreateReferenceEqualityComparer <T>());
     }
     if (typeof(T).IsPrimitive)
     {
         return(SCG.EqualityComparer <T> .Default);
     }
     return(CreateStructComparer <T>());
 }
Exemplo n.º 20
0
        public void UnsequenceEqual_EqualHashCodesNotEquals_False(int[] first, int[] second)
        {
            // Arrange
            Func <int, int, bool> equals           = (x, y) => x == y;
            Func <int, int>       getEqualHashCode = x => 0;
            var comparer = ComparerFactory.CreateEqualityComparer(equals, getEqualHashCode);

            // Act
            var result = first.UnsequenceEqual(second, comparer);

            // Assert
            Assert.That(result, Is.False);
        }
Exemplo n.º 21
0
        public void CanCompareSelectedValue()
        {
            var comparer = ComparerFactory <User> .Create(x => x.Age);

            Assert.That.Comparer().IsCanonical
            (
                value: new User(20),
                less: new User(15),
                equal: new User(20),
                greater: new User(30),
                comparer
            );

            Assert.IsTrue(comparer.Compare(default, new User(0)) < 0);
Exemplo n.º 22
0
        public void UnsequenceEqual_IntialComparer_True(string[] first, string[] second, bool expectedResult)
        {
            // Arrange
            Func <string, string>       firstLetterOrEmpty = s => string.IsNullOrEmpty(s) ? string.Empty : s.Substring(0, 1);
            Func <string, string, bool> equals             = (x, y) => firstLetterOrEmpty(x).Equals(firstLetterOrEmpty(y));
            Func <string, int>          getHashCode        = x => firstLetterOrEmpty(x).GetHashCode();
            var comparer = ComparerFactory.CreateEqualityComparer(equals, getHashCode);

            // Act
            var result = first.UnsequenceEqual(second, comparer);

            // Assert
            Assert.That(result, Is.EqualTo(expectedResult));
        }
Exemplo n.º 23
0
        public void CanCreateComparer1()
        {
            var comparer = ComparerFactory <Product> .Create(
                x => x.Price,
                (builder, x, y) =>
            {
                builder
                .LessThen(() => x < y)
                .Equal(() => x == y)
                .GreaterThan(() => x > y);
            });

            var products = new[]
            {
                new Product {
                    Name = "Car", Price = 7
                },
                new Product {
                    Name = "Table", Price = 3
                },
                new Product {
                    Name = "Orange", Price = 1
                },
            };


            Assert.That.Comparer().IsCanonical
            (
                new Product {
                Price = 3
            },
                new Product {
                Price = 2
            },
                new Product {
                Price = 3
            },
                new Product {
                Price = 4
            },
                comparer
            );

            var sorted = products.OrderByDescending(p => p, comparer).ToList();

            Assert.AreEqual("Car", sorted.ElementAt(0).Name);
            Assert.AreEqual("Table", sorted.ElementAt(1).Name);
            Assert.AreEqual("Orange", sorted.ElementAt(2).Name);
        }
Exemplo n.º 24
0
        public static void SortLists()
        {
            var employees                    = new List <Employee>();
            var employeeByIdComparer         = new EmployeeByIdComparer();
            Comparison <Employee> comparison = (x, y) => x.Id.CompareTo(x.Id);

            employees.Sort(employeeByIdComparer);

            employees.Sort(comparison);

            var set = new SortedSet <Employee>(employeeByIdComparer);

            var comparer = ComparerFactory.Create(comparison);
            var set1     = new SortedSet <Employee>(comparer);
        }
Exemplo n.º 25
0
        public void Keys_returns_GuardedSorted()
        {
            var reverse = ComparerFactory <int> .CreateComparer((a, b) => a > b? -1 : 1);

            var source = new SortedArrayDictionary <int, string>(reverse)
            {
                [1] = "one",
                [2] = "two",
                [3] = "three"
            };

            var guarded = new GuardedSortedDictionary <int, string>(source);

            Assert.IsAssignableFrom <GuardedSorted <int> >(guarded.Keys);
        }
Exemplo n.º 26
0
        public void Values_returns_Values()
        {
            var reverse = ComparerFactory <int> .CreateComparer((a, b) => a > b? -1 : 1);

            var source = new SortedArrayDictionary <int, string>(reverse)
            {
                [1] = "one",
                [2] = "two",
                [3] = "three"
            };

            var guarded = new GuardedSortedDictionary <int, string>(source);

            CollectionAssert.AreEquivalent(new[] { "one", "two", "three" }, guarded.Values);
        }
Exemplo n.º 27
0
        public int Compare(T x, T y)
        {
            var comparers = ComparerFactory.GetComparers <T>();

            foreach (var comparer in comparers)
            {
                var comparisionResult = comparer.Compare(x, y);
                if (comparisionResult.FoundResult)
                {
                    return(comparisionResult.Result);
                }
            }

            return(ComparerFactory.GetDefaultComparer <T>().Compare(x, y));
        }
Exemplo n.º 28
0
        public void Add_ManyItems_Equivalent()
        {
            // Arrange
            var referenceEqualityComparer = ComparerFactory.CreateReferenceEqualityComparer <string>();
            var collection = GetEmptyExtensible(referenceEqualityComparer);
            var count      = Random.Next(100, 250);
            var items      = GetStrings(Random, count);

            // Act
            foreach (var item in items)
            {
                collection.Add(item); // TODO: Verify that items were added?
            }

            // Assert
            Assert.That(collection, Is.EquivalentTo(items));
        }
Exemplo n.º 29
0
        private IPriorityQueue <int> InitializePriorityQueue()
        {
            IComparer <int> weightComparer = ComparerFactory <int> .CreateComparer(
                (a, b) => _distance[a].CompareTo(_distance[b]));

            IPriorityQueue <int> priorityQueue =
                new IntervalHeap <int>(weightComparer);

            _queueItemHandles = new IPriorityQueueHandle <int> [_nodes.Count];
            for (var i = 0; i < _nodes.Count; i++)
            {
                IPriorityQueueHandle <int> itemHandle = null;
                priorityQueue.Add(ref itemHandle, i);

                _queueItemHandles[i] = itemHandle;
            }

            return(priorityQueue);
        }
Exemplo n.º 30
0
        public static void Main(String[] args)
        {
            // SortedArray<Object> sarr = new SortedArray<Object>();
            var lexico = ComparerFactory <Rec <string, int> > .CreateComparer(
                (r1, r2) =>
            {
                int order = r1.X1.CompareTo(r2.X1);
                return(order == 0 ? r1.X2.CompareTo(r2.X2) : order);
            }
                );

            SortedArray <Rec <string, int> > sarr = new SortedArray <Rec <string, int> >(lexico);

            sarr.Add(new Rec <string, int>("ole", 32));
            sarr.Add(new Rec <string, int>("hans", 77));
            sarr.Add(new Rec <string, int>("ole", 63));
            foreach (Rec <string, int> r in sarr)
            {
                Console.WriteLine(r);
            }
        }
Exemplo n.º 31
0
        public static void Main()
        {
            var lexico = ComparerFactory <Rec <string, int> > .CreateComparer(
                (r1, r2) =>
            {
                int order = r1.X1.CompareTo(r2.X1);
                return(order == 0 ? r1.X2.CompareTo(r2.X2) : order);
            }
                );

            SortedArray <Rec <string, int> > sarr = new SortedArray <Rec <string, int> >(lexico)
            {
                new Rec <string, int>("ole", 32),
                new Rec <string, int>("hans", 77),
                new Rec <string, int>("ole", 63)
            };

            foreach (var r in sarr)
            {
                Console.WriteLine(r);
            }
        }