简体   繁体   中英

How to use a Tuple as a Key in a Dictionary C#

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.

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";

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM