サイズと速度のペアを維持するための構造体を作成します。
public struct SizeSpeedKey
{
public string Size;
public int Speed;
public SizeSpeedKey(string size, int speed)
{
Size = size;
Speed = speed;
}
}
そして、これは、ルックアップコードのようになります。あなたのサイズと速度を仮定し
using System;
using System.Collections.Generic;
namespace LookupTable
{
internal class Program
{
private static readonly Dictionary<SizeSpeedKey, double> lookupTable =
new Dictionary<SizeSpeedKey, double>
{
{new SizeSpeedKey("6x5", 500), 0.1},
{new SizeSpeedKey("6x5", 750), 0.5},
{new SizeSpeedKey("6x4", 500), 0.01},
{new SizeSpeedKey("6x4", 750), 0.1},
{new SizeSpeedKey("8x5", 500), 0.5},
{new SizeSpeedKey("8x5", 750), 0.9},
};
private static void Main(string[] args)
{
// these will of course need to be read from the user
var size = "6x4";
var speed = 500;
Console.WriteLine("For size = {0} and speed = {1}, the pressure will be {2}", size, speed, lookupTable[new SizeSpeedKey(size, speed)]);
Console.ReadLine();
}
}
}
これは機能しません。 SizeSpeedKeyはIEquatableを実装していないので、辞書はどのようにキー値を比較できますか? –
はい、いいえ。辞書は任意のオブジェクトをキーとして使用できます(すべてが.Equalsと.GetHashCodeを提供します)。これらのメソッドをオーバーライドすることなく、同一性を評価するためにアイデンティティが使用されます。今では構造体が常にコピーされているので、 "等しい"値を見つけることは実際には難しいかもしれません^^ 少なくとも、@ rwwildenの例のように.Equalsをオーバーライドする必要があります。 –
うーん...本当、それ。 +1のrwwilden :) –