Home > Backend Development > C++ > How Can I Efficiently Implement a Multi-Key Dictionary in C#?

How Can I Efficiently Implement a Multi-Key Dictionary in C#?

DDD
Release: 2025-01-08 19:11:53
Original
433 people have browsed it

How Can I Efficiently Implement a Multi-Key Dictionary in C#?

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:

  • The default GetHashCode implementation only considers the first field, which leads to potential scalability issues.
  • Null values ​​complicate matters.

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template