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

送分小仙女□ 提交于 2019-12-30 08:13:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!