• Stars
    star
    400
  • Rank 107,843 (Top 3 %)
  • Language
    C#
  • License
    MIT License
  • Created over 10 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

The last comparison library you'll ever need!

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".

More Repositories

1

AsyncEx

A helper library for async/await.
C#
3,295
star
2

StructuredConcurrency

Structured concurrency support for C#
C#
203
star
3

Mvvm

MVVM helpers, including calculated properties and asynchronous notification tasks.
C#
132
star
4

AspNetBackgroundTasks

A component that registers "fire and forget" tasks with the ASP.NET runtime.
C#
109
star
5

Deque

Double-ended queue
C#
105
star
6

Disposables

IDisposable helper types.
C#
98
star
7

CalculatedProperties

Easy-to-use calculated properties for MVVM apps
C#
73
star
8

AsyncDiagnostics

Easy-to-use exception causality chains for async/await.
C#
61
star
9

BrowserBoss

Easily script browsers.
C#
55
star
10

Try

The Try monad (Error/Exceptional monad) for C#
C#
44
star
11

ConnectedProperties

Dynamically attach properties to (almost) any object instance.
C#
41
star
12

Guids

Helper types for creating and interpreting GUIDs.
C#
27
star
13

Presentations

Repository for presentations
C#
27
star
14

PegLeg

A PEG parser for C#, using code generators
C#
22
star
15

CrossDomainSingleton

An AppDomain-aware, thread-safe singleton that ensures only one instance exists in the entire application.
C#
22
star
16

LocalTelemetry

Local dashboards for telemetry collection.
18
star
17

Docs

Documentation of various and sundry matters
16
star
18

grounded-chatgpt

ChatGPT, but grounded in custom data
C#
16
star
19

HashAlgorithms

CRC calculation for .NET
C#
16
star
20

DependencyInjection

Helpers for Microsoft.Extensions.DependencyInjection.
C#
15
star
21

ArraySegments

A library for slicing and dicing arrays (without copying).
C#
13
star
22

Scripts

Misc single-file scripts and utilities
C#
13
star
23

ArcDb

An ACID .NET relational database
12
star
24

Mvvm.CalculatedProperties

Automatically raise PropertyChanged in MVVM applications.
C#
11
star
25

Cancellation

Types to assist with cancellation handling.
C#
11
star
26

DisplayProfiles

An application that saves and restores display monitor layouts.
C#
10
star
27

Mvvm.Core

Basic MVVM helpers.
C#
10
star
28

AsyncCTPUtil

Utility code originally distributed as part of the Async CTP
C#
10
star
29

ProjProps

A dotnet tool that displays project properties.
C#
10
star
30

Logging

Library for using scopes with Microsoft.Extensions.Logging.
C#
10
star
31

AsyncEx.Testing

Helper types for writing unit tests for asynchronous code.
C#
9
star
32

ProducerConsumerStream

A producer/consumer collection of bytes with a Stream-based API.
C#
8
star
33

OptionParsing

Flexible command-line parsing library
C#
8
star
34

BuildTools

Miscellaneous tools for building .NET Core libraries.
7
star
35

UniformResourceIdentifiers

Standard-compliant URI encoders and parsers
C#
6
star
36

iterjs

ES6 library for working with iterables and iterators
JavaScript
5
star
37

Quicly

An implementation of IETF QUIC in .NET
C#
4
star
38

StrongNamer

Simple app that strong-names NuGet packages.
C#
3
star
39

AsyncUnitTests

Helpers for async unit testing.
C#
3
star
40

blog-stephencleary-dotcom

blog.stephencleary.com
HTML
2
star
41

Hosting

.NET Generic Host for UI applications
C#
2
star
42

Collections.Async

Async-compatible producer/consumer collections.
2
star
43

comments.stephencleary.com

Comments for stephencleary.com.
JavaScript
2
star
44

stephencleary-dotcom

HTML
1
star
45

LoggerProviderHelpers

Helper types for implementing Microsoft's ILoggerProvider.
1
star
46

ARC

A simple dynamic language. Like JavaScript, but better!
C#
1
star
47

DockerLifetime

A .NET Core lifetime service for Docker containers
1
star
48

glob

GitHub Action that finds files using globs (wildcards)
JavaScript
1
star
49

Presentations-IntermediateAsync

Sample code for presentation given at GRDevDay 2013-03-02
1
star
50

Hymnals

Public domain hymnals
LilyPond
1
star