Implementation method of C# multi-key dictionary
The .NET Base Class Library (BCL) does not have a built-in multi-key dictionary, but there are some open source options available.
Use tuples as keys
A common approach is to use tuples as keys. However, this method has some disadvantages:
Custom tuple structure
To work around these limitations, you can define a custom tuple structure:
<code class="language-csharp">public struct Tuple<T1, T2> { public readonly T1 Item1; public readonly T2 Item2; public Tuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; } }</code>
This provides immutability, pre-computed hash codes and equality comparisons. Best practice is to put the most distinguishing fields in the first item.
ValueUtils library implements better hashing algorithm
The ValueUtils library provides a FieldwiseHasher.Hash method, which can create a more reliable hash code for the structure and solves the problem of poor GetHashCode implementation for tuples.
Named value objects improve readability
ValueUtils also allows the use of named fields in multi-field keys, improving code readability:
<code class="language-csharp">sealed class MyValueObject : ValueObject<MyValueObject> { public DayOfWeek day; public string NamedPart; }</code>
With this approach, data with value semantics can have both named members and correct hash codes until native support for named tuples with good hash codes is implemented in a future C# version.
The above is the detailed content of How Can I Efficiently Implement a Multi-Key Dictionary in C#?. For more information, please follow other related articles on the PHP Chinese website!