简体   繁体   English

如何在字典C#中使用元组作为键

[英]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. 我有一个Dictionary fieldTracker ,它将Tuple<int, int>作为Key,将string作为值。 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. 我在Microsoft文档中搜索了一下,但找不到这个问题的关键

dict[Tuple.Create(1, 1)] = "Hello";

or with C#7 ValueTuple : 或者使用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 :) 希望这可以帮助 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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