二维数组,可以用于 物品ID 和 物品 名称 的预设置。
Dictionary<string, string> testDict = new Dictionary<string, string>() { ["key1"] = "value1", ["key2"] = "value2" };
var testDict = new Dictionary<string, string>() { ["key1"] = "value1", ["key2"] = "value2" };
查找的 变量 必须 唯一
...
using System;
using System.Collections.Generic;
...
var testDict = new Dictionary<string, string>() { ["key1"] = "value1", ["key2"] = "value2" };
...
if (test_array.ContainsKey(1))//通过int变量 来查找 对应 的字符串
{
string value = test_array[1];
//Console.WriteLine(value);
Debug.Log(value);//输出:test1
}//https://www.codegrepper.com/code-examples/csharp/c%23+dictionary+get+value+by+key
string value = "0";
test_array.TryGetValue(2,out value);//https://www.dotnetperls.com/dictionary
Debug.Log(value);
...
public static Dictionary<int, string> test_array =
new Dictionary<int, string>()
{
{1,"test1"},
{2,"test2"},
{5,"test2"},
{66,"test2"}
};
...
怎么通过字符串 找到 对应的int 数字或者 int 数组?
用foreach循环进行查找
...
using System.Collections.Generic;
...
public List<int> list_k = new List<int>();
...
int k = 0;string getValue = "test2";
foreach (KeyValuePair<int, string> v in test_array)
{
if (!test_array.ContainsValue(getValue))
{
return;
}
if (v.Value == getValue)
{
list_k.Add(v.Key);//通过dictionary的value,字符串关键字 找到了 dictionary的key
}
//Debug.Log(k + " ???: "+v.Key +"/"+ v.Value);
k++;
}
string value_1 = "-1";
if (list_k.Count > 0)
{
for (int i=0; i < list_k.Count; i++)
{
test_array.TryGetValue(list_k[i], out value_1);
Debug.Log(i+" : "+ list_k [i]+ "/"+ value_1);
}
}
...
public static Dictionary<int, string> test_array =
new Dictionary<int, string>()
{
{1,"test1"},
{2,"test2"},
{5,"test2"},
{66,"test2"}
};
...
输出
2
5
66
用for循环进行查找
...
Debug.Log(" ????????????: " + test_array.Count);
if (test_array.Count > 0)
{
int[] keys = new int[test_array.Keys.Count];
test_array.Keys.CopyTo(keys, 0);
for (int i = 0; i < keys.Length; ++i)
{
if (test_array[keys[i]] == getValue)
{
Debug.Log(keys[i]+"/"+test_array[keys[i]]);//通过dictionary的value,字符串关键字 找到了 dictionary的key
}
}
}
...
public static Dictionary<int, string> test_array =
new Dictionary<int, string>()
{
{1,"test1"},
{2,"test2"},
{5,"test2"},
{66,"test2"}
};
...
输出
2
5
66
参考资料:
1.c# dictionary get value by key
4.“unity dictionary initilize with values” Code Answer
5.
6.

这篇博客探讨了在Unity中如何利用C#的Dictionary数据结构,通过唯一的字符串关键字来查找并获取对应的int数值或字符串数组。文章展示了如何初始化二维数组和Dictionary,并提供了使用foreach和for循环进行查找的方法及示例代码。

被折叠的 条评论
为什么被折叠?



