c# - 我应该使用什么数据结构?

标签 c# data-structures

我有一个问题,我需要将两个输入映射到一个输出。

我知道字典是一般类型的线性映射:

for every x (key) there may be a y (value)

我需要的是多维映射:

for every x,y (key) there may be a z (value)

当然,更重要的是我需要它来支持通用类型和动态调整大小。

此数据结构是否存在于 C# 中,还是我必须创建字典的字典?如果没有必要,我宁愿不重新发明轮子。


重新发明轮子:

using System;
using System.Collections.Generic;
using System.Text;

namespace zlib.Collections
{
    public class Dictionary3D<Tx, Ty, Tz>
    {
        private Dictionary<Tuple<Tx, Ty>, Tz> _dict = new Dictionary<Tuple<Tx, Ty>, Tz>();

        public void Add(Tx x, Ty y, Tz z)
        {
            _dict.Add(Tuple.Create<Tx, Ty>(x, y), z);
        }

        public void Clear()
        {
            _dict.Clear();
        }

        public bool ContainsKey(Tx x, Ty y)
        {
            return _dict.ContainsKey(Tuple.Create<Tx, Ty>(x, y));
        }

        public bool ContainsValue(Tz z)
        {
            return _dict.ContainsValue(z);
        }

        public Dictionary<Tuple<Tx, Ty>, Tz>.Enumerator GetEnumerator()
        {
            return _dict.GetEnumerator();
        }

        public bool Remove(Tx x, Ty y)
        {
            return _dict.Remove(Tuple.Create<Tx, Ty>(x, y));
        }

        public bool TryGetValue(Tx x, Ty y, out Tz z)
        {
            return _dict.TryGetValue(Tuple.Create<Tx, Ty>(x, y), out z);
        }

        public int Count
        {
            get { return _dict.Count; }
        }

        public Dictionary<Tuple<Tx,Ty>,Tz>.KeyCollection Keys
        {
            get
            {
                return _dict.Keys;
            }
        }

        public Dictionary<Tuple<Tx, Ty>, Tz>.ValueCollection Values
        {
            get
            {
                return _dict.Values;
            }
        }

        public Tz this[Tx x, Ty y]
        {
            get
            {
                return _dict[Tuple.Create<Tx, Ty>(x, y)];
            }
            set
            {
                _dict[Tuple.Create<Tx, Ty>(x, y)] = value;
            }
        }
    }
}

似乎重新发明轮子在回应中胜出。这是我到目前为止想出的代码,但我觉得应该有更好的方法,比如 matrix 或其他东西。

最佳答案

关于

   Dictionary<Tuple<T,K>,Tuple<L,J>> 

??

关于c# - 我应该使用什么数据结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7855678/

相关文章:

c# - 如何绑定(bind)静态BitmapSource?

c - 程序在单链表中插入一个元素

c - 算法 : To determine whether a given set has two subsets which are disjoint such that sum of elements in both subsets is same?

c++ - 如何从外部函数 C++ 访问动态结构?

c# - ASP.NET Core 1.0 POST IEnumerable<T> 到 Controller

c# - 数组与数组列表的显着差异?

c# - 尝试使用 Image.Save 时出现 "A generic error occurred in GDI+"

c# - 带有嵌套模型类的 Razor View

c - 访问结构中声明的指针的内容

algorithm - 使用广度优先搜索和中序遍历来分析一个非常大的二叉搜索树的有效性