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

How to Implement a Multi-Key Dictionary in C#?

Barbara Streisand
Barbara StreisandOriginal
2025-01-08 19:26:42422browse

How to Implement a Multi-Key Dictionary in C#?

Multi-key dictionary in C#

C# itself does not support the data structure of multi-key dictionary. However, some open source libraries provide this functionality.

Tuple-based implementation

A common approach is to use tuples as keys. A tuple is a data structure that represents a collection of multiple values, each with its own type. For example, the following code defines a tuple containing two keys (a string and an integer):

<code class="language-csharp">var tuple = (key1: "key1", key2: 1);</code>

You can then use the tuple as the key of the dictionary:

<code class="language-csharp">var dictionary = new Dictionary<Tuple<string, int>, string>();
dictionary.Add(tuple, "value");</code>

Structure-based implementation

Another option is to define a custom structure to represent the multi-key value. The following code defines a structure with two fields:

<code class="language-csharp">public struct Key
{
    public string Key1 { get; set; }
    public int Key2 { get; set; }
}</code>

You can then use the struct as a key to a dictionary:

<code class="language-csharp">var dictionary = new Dictionary<Key, string>();
dictionary.Add(new Key { Key1 = "key1", Key2 = 1 }, "value");</code>

Value object implementation

A more sophisticated approach is to define a class to encapsulate multiple values ​​and enforce value semantics. This approach provides a concise and easy-to-maintain way to handle multi-key data. The following code defines a value object with two fields:

<code class="language-csharp">public class ValueObject
{
    public string Key1 { get; private set; }
    public int Key2 { get; private set; }

    public ValueObject(string key1, int key2)
    {
        Key1 = key1;
        Key2 = key2;
    }

    public override bool Equals(object obj)
    {
        return obj is ValueObject other &&
               other.Key1 == Key1 &&
               other.Key2 == Key2;
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(Key1, Key2);
    }
}</code>

You can then use the value object as the key of the dictionary:

<code class="language-csharp">var dictionary = new Dictionary<ValueObject, string>();
dictionary.Add(new ValueObject("key1", 1), "value");</code>

The above is the detailed content of How to Implement a Multi-Key Dictionary in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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