コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【C#】Dictionary のキーに複数の値を設定する方法

構造体を使用する方法

using System;
using System.Collections.Generic;

public static class Program
{
    // 構造体でキー用のデータを定義
    public struct KeyData
    {
        public int m_series;
        public int m_number;
        
        public KeyData( int series, int number )
        {
            m_series = series;
            m_number = number;
        }
    }

    private static void Main()
    {
        var table = new Dictionary<KeyData, string>
        {
            { new KeyData( 1, 1 ), "フシギダネ" },
            { new KeyData( 1, 2 ), "フシギソウ" },
            { new KeyData( 1, 3 ), "フシギバナ" },
            { new KeyData( 2, 1 ), "チコリータ" },
            { new KeyData( 2, 2 ), "ベイリーフ" },
            { new KeyData( 2, 3 ), "メガニウム" },
        };

        Console.WriteLine( table[ new KeyData( 1, 1 ) ] ); // フシギダネ
        Console.WriteLine( table[ new KeyData( 1, 2 ) ] ); // フシギソウ
        Console.WriteLine( table[ new KeyData( 1, 3 ) ] ); // フシギバナ
        Console.WriteLine( table[ new KeyData( 2, 1 ) ] ); // チコリータ
        Console.WriteLine( table[ new KeyData( 2, 2 ) ] ); // ベイリーフ
        Console.WriteLine( table[ new KeyData( 2, 3 ) ] ); // メガニウム
    }
}

Tuple を使用する方法

using System;
using System.Collections.Generic;

public static class Program
{
    private static void Main()
    {
        var table = new Dictionary<Tuple<int, int>, string>
        {
            { Tuple.Create( 1, 1 ), "フシギダネ" },
            { Tuple.Create( 1, 2 ), "フシギソウ" },
            { Tuple.Create( 1, 3 ), "フシギバナ" },
            { Tuple.Create( 2, 1 ), "チコリータ" },
            { Tuple.Create( 2, 2 ), "ベイリーフ" },
            { Tuple.Create( 2, 3 ), "メガニウム" },
        };

        Console.WriteLine( table[ Tuple.Create( 1, 1 ) ] ); // フシギダネ
        Console.WriteLine( table[ Tuple.Create( 1, 2 ) ] ); // フシギソウ
        Console.WriteLine( table[ Tuple.Create( 1, 3 ) ] ); // フシギバナ
        Console.WriteLine( table[ Tuple.Create( 2, 1 ) ] ); // チコリータ
        Console.WriteLine( table[ Tuple.Create( 2, 2 ) ] ); // ベイリーフ
        Console.WriteLine( table[ Tuple.Create( 2, 3 ) ] ); // メガニウム
    }
}

ValueTuple を使用する方法

using System;
using System.Collections.Generic;

public static class Program
{
    private static void Main()
    {
        var table = new Dictionary<(int, int), string>
        {
            { ( 1, 1 ), "フシギダネ" },
            { ( 1, 2 ), "フシギソウ" },
            { ( 1, 3 ), "フシギバナ" },
            { ( 2, 1 ), "チコリータ" },
            { ( 2, 2 ), "ベイリーフ" },
            { ( 2, 3 ), "メガニウム" },
        };

        Console.WriteLine( table[ ( 1, 1 ) ] ); // フシギダネ
        Console.WriteLine( table[ ( 1, 2 ) ] ); // フシギソウ
        Console.WriteLine( table[ ( 1, 3 ) ] ); // フシギバナ
        Console.WriteLine( table[ ( 2, 1 ) ] ); // チコリータ
        Console.WriteLine( table[ ( 2, 2 ) ] ); // ベイリーフ
        Console.WriteLine( table[ ( 2, 3 ) ] ); // メガニウム
    }
}
  • .NET Framework 4.7 以上の場合に使用できます