Skip to content

Latest commit

 

History

History

Gapotchenko.FX.Tuples

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Gapotchenko.FX.Tuples

License NuGet

The module provides extended functionality for .NET tuples represented by System.Tuple and System.ValueTuple types.

Equality Comparer for Value Tuples

In .NET, value tuples are represented by System.ValueTuple type. They allow to quickly pack several values together without creating dedicated types for that.

Value tuples come with sane defaults, but sometimes you may need custom equality comparers for them. Let's take a look at example:

HashSet<(string, int)> database =
    new()
    {
        // name, age
        ("Alice", 32),
        ("Bob", 40),
        ("John", 14)
    };

Let's suppose that we need to search for records in that database by name and age but ignoring the case of letters in the name. The default value tuple equality comparer is case-sensitive for strings, so the following database query will be unsuccessful:

Console.WriteLine("The query result: {0}.", database.Contains(("john", 14)));
// The query result: False.

One way to fix that is to manually create a custom IEqualityComparer<(T1, T2)> implementation and pass it to the constructor of the HashSet class. Another more simple way to solve the problem is to use Gapotchenko.FX.Tuples.ValueTupleEqualityComparer class to quickly create a specialized equality comparer that fits our needs:

// Create a custom equality comparer for (string, int) value tuple.
var comparer = ValueTupleEqualityComparer.Create<string, int>(
    StringComparer.CurrentCultureIgnoreCase, // ignore case for strings
    null); // use a default comparer for integers

HashSet<(string, int)> database =
    new(comparer)
    {
        ("Alice", 32),
        ("Bob", 40),
        ("John", 14)
    };

Console.WriteLine("The query result: {0}.", database.Contains(("john", 14)));

Now the code works as expected:

The query result: True.

Equality Comparer for Tuples

Tuples are represented by System.Tuple types. The main difference of tuples from value tuples is that System.Tuple types are classes while System.ValueTuple types are structures. The remaining part of the concept is almost the same.

Gapotchenko.FX.Tuples module allows you to create custom equality comparers for tuples by using TupleEqualityComparer class and its Create methods.

Usage

Gapotchenko.FX.Tuples module is available as a NuGet package:

PM> Install-Package Gapotchenko.FX.Tuples

Other Modules

Let's continue with a look at some other modules provided by Gapotchenko.FX:

Or look at the full list of modules.