因为在嵌套使用switch case过程中用到的case太多,所以想创建一个Dictionary<KeyValuePair<int, int>, string>集合,KeyValuePair的key和value都是0-100的int整数,类似[[0,0],"aaa"] [[0,1],"aaa"].........,[[99,98],"aaa"] [[99,99],"aaa"]..,求高手指教赋值方法
Dictionary<KeyValuePair<int, int>, string> d = new Dictionary<KeyValuePair<int, int>, string>();
for(int i=0;i<100;i++)
for(int j=0;j<100;j++)
d.Add(new KeyValuePair<int, int>(i, j),"aaa");
非常感谢你的帮助,因为要反复进行取值操作,我用的方法有点笨拙d[new KeyValuePair<int,int>(1,2)]
,请你赐教下比较灵活的取值方法,谢谢
@梦天涯: 你可以根据具体需求写个扩展方法!
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Dictionary<KeyValuePair<int, int>, string> d = new Dictionary<KeyValuePair<int, int>, string>(); for (int i = 0; i < 100; i++) for (int j = 0; j < 100; j++) d.Add(new KeyValuePair<int, int>(i, j), "aaa"); string s = d.GetVal(2, 3); Console.WriteLine(s); Console.ReadKey(); } } public static class DictionaryExtension { public static string GetVal(this Dictionary<KeyValuePair<int, int>, string> d, int key, int value) { return d[new KeyValuePair<int, int>(key, value)]; } } }
可以使用Tuple<int,int>替代KeyValuePair<int, int>。
我想,如果传入一个KeyValuePair<int, int>应该从字典里拿不到东西吧。(只是猜测)
Dictionary<KeyValuePair<int, int>, string> dict = new Dictionary<KeyValuePair<int, int>, string>();
dict[new KeyValuePair<int, int>(0, 0)] = "aaa";
dict[new KeyValuePair<int, int>(99, 99)] = "aaa";
1 Dictionary<KeyValuePair<int,int>,string> dic = new Dictionary<KeyValuePair<int, int>, string>(); 2 3 4 dic.Add(new KeyValuePair<int, int>(1,1),"1" ); 5 6 dic.Add(new KeyValuePair<int, int>(2, 2), "2"); 7 8 foreach (var item in dic) 9 { 10 Console.WriteLine(string.Format("keykey:{0},keyvalue:{1},value:{2}", item.Key.Key, item.Key.Value, item.Value)); 11 } 12 13 Console.WriteLine(dic[new KeyValuePair<int, int>(1,1)]); 14 15 Console.ReadLine();
其实插入很简单,但是这种读取也会很麻烦,其实可以把前面的KeyValuePair换成string的,[[0,0],"aaa"] ,用["0,0","aaa"]表示,string用,splite下就可以获取了。