将值分配给键类型为 <Tuple<int,int> C# 的字典

nic*_*wdy 3 c# dictionary tuples key-value

我编写代码来生成一个应该是图形编辑器的网格。网格值包含在字典中。这是我生成字典对象的方法,让您了解我正在处理的内容。

public Dictionary<Tuple<int, int>, string> GenerateTable(int _x, int _y)
        {
            int total = _x * _y;
            var grid = new Dictionary<Tuple<int, int>, string>(); //!Might need this later!

            for (int i = 1; i <= _x; i++) // outer loop is column 
            {
                for (int ii = 1; ii <= _y; ii++) // Inner loop is row -
                {
                    grid.Add(Tuple.Create(i, ii), "O");
                }
            }
            return grid; // Should have same amount of elements as int total
        }
Run Code Online (Sandbox Code Playgroud)

我有另一种方法,我想更改字典中的一个元素,因为我使用的是元组的键,我不知道在索引中提供什么来更改值。这是另一种方法。

 public void ColorPixel(Dictionary<Tuple<int, int>, string> _table, int _x, int _y, string _c)
        {
            foreach(var pixel in _table
                .Where(k => k.Key.Item1 == _x && k.Key.Item2 == _y))
            {

            }


            //var tbl = _table.
            //    Where(t => t.Key.Item1 == _x && t.Key.Item2 == _y)
            //    .Select(t => t.Value == _c);

        }
Run Code Online (Sandbox Code Playgroud)

有谁知道如何通过访问 Tuple 类型的键来更改字典中的元素?

cyn*_*nic 5

Tuple类型是“结构上可比较的”。这意味着要访问以 1 为键的字典中的值,您需要创建该元组的一个新实例,并以您认为合适的任何方式(索引器TryGetValue等)访问该值。

var key = Tuple.Create(x, y);
var value = dictionary[key];
Run Code Online (Sandbox Code Playgroud)

  • “结构可比性”在这里并不真正相关。相关信息是“Tuple&lt;,&gt;”覆盖了“Equals”和“GetHashCode”并提供了坐标方式的实现。这与“结构 **equatable**” 实现具有相同的行为。例如,如果您想要一个`SortedDictionary&lt;Tuple&lt;,&gt;,&gt;`,那么“可比较”的东西可能是相关的。 (2认同)