问题
I have a Dictionary fieldTracker
which takes a Tuple<int, int>
as Key and string
as value. However, I can't seem to find the right way to access the value. Here is my current code:
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 5; j++)
dict.Add(new Tuple<int, int>(i, j), "");
}
dict[(1,1)] = "Hello";
I've searched around a bit in the Microsoft documentation, but can't find the key to this problem.
回答1:
dict[Tuple.Create(1, 1)] = "Hello";
or with C#7 ValueTuple:
var dict = new Dictionary<(int, int), string>();
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 5; j++)
dict.Add((i, j), "");
}
dict[(1, 1)] = "Hello";
回答2:
You can try this way.
var dict = new Dictionary<Tuple<int, int>, string>();
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 5; j++)
dict.Add(Tuple.Create<int, int>(i, j), "Hello");
}
string val = dict[Tuple.Create<int, int>(1,1)];
Hope this helps :)
来源:https://stackoverflow.com/questions/52220354/how-to-use-a-tuple-as-a-key-in-a-dictionary-c-sharp