All Projects → StephenCleary → Comparers

StephenCleary / Comparers

Licence: mit
The last comparison library you'll ever need!

Projects that are alternatives of or similar to Comparers

pybraincompare
brain image comparison and visualization methods for python!
Stars: ✭ 16 (-94.98%)
Mutual labels:  comparison
Jquery Tablesort
A tiny & dead-simple jQuery plugin for sortable tables.
Stars: ✭ 254 (-20.38%)
Mutual labels:  sort
Semver
Semantic version parsing and comparison.
Stars: ✭ 283 (-11.29%)
Mutual labels:  comparison
image-classifier-service
Sorting my messed folder where I put my holidays pictures was not fun. My computer made the trick for me with Deep Learning!
Stars: ✭ 31 (-90.28%)
Mutual labels:  sort
Yolov5-deepsort-driverDistracted-driving-behavior-detection
基于深度学习的驾驶员分心驾驶行为(疲劳+危险行为)预警系统使用YOLOv5+Deepsort实现驾驶员的危险驾驶行为的预警监测
Stars: ✭ 107 (-66.46%)
Mutual labels:  sort
Mega Interview Guide
The MEGA interview guide, JavaSciript, Front End, Comp Sci
Stars: ✭ 255 (-20.06%)
Mutual labels:  sort
sort-js-object-keys
This is a VS code extension to alphabetically sort the keys in selected js objects keys in your code.
Stars: ✭ 21 (-93.42%)
Mutual labels:  sort
Klib
A standalone and lightweight C library
Stars: ✭ 3,442 (+979%)
Mutual labels:  sort
Image-Sort
Sorts your image at high speed
Stars: ✭ 15 (-95.3%)
Mutual labels:  sort
Gridjs
Advanced table plugin
Stars: ✭ 3,231 (+912.85%)
Mutual labels:  sort
catch-lest-other-comparison
Tabularised feature comparison between Catch, doctest and lest C++ test frameworks
Stars: ✭ 20 (-93.73%)
Mutual labels:  comparison
case-insensitive
Case insensitive string comparison
Stars: ✭ 24 (-92.48%)
Mutual labels:  comparison
Jschema
A simple, easy to use data modeling framework for JavaScript
Stars: ✭ 261 (-18.18%)
Mutual labels:  sort
Multi-Face-Comparison
This repo is meant for backend API for face comparision and computer vision. It is built on python flask framework
Stars: ✭ 20 (-93.73%)
Mutual labels:  comparison
Rust Os Comparison
A comparison of operating systems written in Rust
Stars: ✭ 292 (-8.46%)
Mutual labels:  comparison
todo-txt
Todo.txt syntax highlighter and helper extension for visual studio code.
Stars: ✭ 39 (-87.77%)
Mutual labels:  sort
Gostl
Data structure and algorithm library for go, designed to provide functions similar to C++ STL
Stars: ✭ 254 (-20.38%)
Mutual labels:  sort
Algods
Implementation of Algorithms and Data Structures, Problems and Solutions
Stars: ✭ 3,295 (+932.92%)
Mutual labels:  sort
Data Structure Php Clanguage
对于数据结构和算法类的东西,我工作有些年份了,大学也有所涉猎,积累了一些内容,不高产不母猪,打我自己脸
Stars: ✭ 299 (-6.27%)
Mutual labels:  sort
Graphql To Mongodb
Allows for generic run-time generation of filter types for existing graphql types and parsing client requests to mongodb find queries
Stars: ✭ 261 (-18.18%)
Mutual labels:  sort

Logo

Comparers Build status codecov NuGet version API docs

The last comparison library you'll ever need! Wide platform support; fluent syntax.

Creating Comparers

Install the Nito.Comparers NuGet package. By default, this includes the extension package for LINQ support. There are also extension packages available for System.Reactive (Rx) and System.Interactive (Ix) support.

The comparer types are in the namespace Nito.Comparers.

Let's say you've got a collection of your POCOs:

class Person
{
    public string FirstName { get; }
    public string LastName { get; }
}
List<Person> list = ...;

Here's an easy way to sort them all by last name and then first name:

IComparer<Person> nameComparer =
    ComparerBuilder.For<Person>()
                   .OrderBy(p => p.LastName)
                   .ThenBy(p => p.FirstName);
list.Sort(nameComparer);

Implementing Comparable Types

How about having Person implement it? Let's face it: implementing comparison in .NET is a real pain. IComparable<T>, IComparable, IEquatable<T>, Object.Equals, and Object.GetHashCode?!?! But it's easy with a base type:

class Person : ComparableBase<Person>
{
    static Person()
    {
        DefaultComparer =
            ComparerBuilder.For<Person>()
                           .OrderBy(p => p.LastName)
                           .ThenBy(p => p.FirstName);
    }

    public string FirstName { get; }
    public string LastName { get; }
}

ComparableBase<T> auto-magically implements all the comparable interfaces, including correct overrides of Object.Equals and Object.GetHashCode.

Using Comparers in Hash Containers

What about hash-based containers? Every single comparer produced by the Comparers library also implements equality comparison!

IEqualityComparer<Person> nameComparer =
    ComparerBuilder.For<Person>()
                   .OrderBy(p => p.LastName)
                   .ThenBy(p => p.FirstName);
Dictionary<Person, Address> dict = new Dictionary<Person, Address>(nameComparer);

Equality Comparers

Sometimes, you can only define equality. Well, good news: there are equality comparer types that parallel the full comparer types.

class Entity : EquatableBase<Entity>
{
    static Entity()
    {
        DefaultComparer =
            EqualityComparerBuilder.For<Entity>()
                                   .EquateBy(e => e.Id);
    }

    public int Id { get; }
}

Working with Sequences

Sequences are sorted lexicographically. The Sequence operator takes an existing comparer for one type, and defines a lexicographical comparer for sequences of that type:

var nameComparer =
    ComparerBuilder.For<Person>()
                   .OrderBy(p => p.LastName)
                   .ThenBy(p => p.FirstName);
List<IEnumerable<Person>> groups = ...;
groups.Sort(nameComparer.Sequence());

There's also natural extensions for LINQ, Rx, and Ix that allow you to define comparers on-the-fly (particularly useful for anonymous types):

IEnumerable<Person> people = ...;
var anonymousProjection = people.Select(x => new { GivenName = x.FirstName, Surname = x.LastName });
var reduced = anonymousProjection.Distinct(c => c.EquateBy(x => x.Surname));

Dynamic Sorting

Need to sort dynamically at runtime? No problem!

var sortByProperties = new[] { "LastName", "FirstName" };
IComparer<Person> comparer = ComparerBuilder.For<Person>().Null();
foreach (var propertyName in sortByProperties)
{
    var localPropertyName = propertyName;
    Func<Person, string> selector = p => p.GetType().GetProperty(localPropertyName).GetValue(p, null) as string;
    comparer = comparer.ThenBy(selector);
}

Complex Sorting

Want a cute trick? Here's one: true is "greater than" false, so if you want to order by some weird condition, it's not too hard:

// Use the default sort order (last name, then first name), EXCEPT all "Smith"s move to the head of the line.
var comparer =
    ComparerBuilder.For<Person>()
                   .OrderBy(p => p.LastName == "Smith", descending: true)
                   .ThenBy(ComparerBuilder.For<Person>().Default());
list.Sort(comparer);

By default, null values are "less than" anything else, but you can use the same sort of trick to sort them as "greater than" non-null values (i.e., nulls will be last in a sorted collection):

List<int?> myInts = ...;
var comparer =
    ComparerBuilder.For<int?>()
                   .OrderBy(i => i == null, specialNullHandling: true)
                   .ThenBy(ComparerBuilder.For<int?>().Default());
myInts.Sort(comparer);
// Note: we need to pass "specialNullHandling"; otherwise, the default null-ordering rules will apply.

More?!

For full details, see the detailed docs.

What's with the flying saucer?

Other languages provide a comparison operator <=>, which is called the "spaceship operator". This library provides similar capabilities for C#, hence the "spaceship logo".

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].