The module provides extended functionality for .NET tuples represented by System.Tuple
and System.ValueTuple
types.
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.
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.
Gapotchenko.FX.Tuples
module is available as a NuGet package:
PM> Install-Package Gapotchenko.FX.Tuples
Let's continue with a look at some other modules provided by Gapotchenko.FX:
- Gapotchenko.FX
- Gapotchenko.FX.AppModel.Information
- Gapotchenko.FX.Collections
- Gapotchenko.FX.Console
- Gapotchenko.FX.Data
- Gapotchenko.FX.Diagnostics
- Gapotchenko.FX.IO
- Gapotchenko.FX.Linq
- Gapotchenko.FX.Math
- Gapotchenko.FX.Memory
- Gapotchenko.FX.Security.Cryptography
- Gapotchenko.FX.Text
- Gapotchenko.FX.Threading
- ➴ Gapotchenko.FX.Tuples
Or look at the full list of modules.