Dictionaries are unique to Lists, because they are associated by key value pair.
C# Dictionary
KEY:
declare a dictionary. TKey and TValue are the data types (int , string, and even class) .
public Dictionary<int, string> database = new Dictionary<int, string>();
和List对比一下 声明和添加以及使用
public class ItemDB : MonoBehaviour
{
public List<Item> itemList = new List<Item>();
public Dictionary<int, Item> itemDict = new Dictionary<int, Item>();
private void Start()
{
itemList.Add(new Item());
itemDict.Add(0, new Item());
itemDict.Add(1, new Item(1, "sjdiajsd"));
var item = itemDict[0];
}
}
C# Dictionary: Looping through dictionary
我们在写loop的时候通常直接这样子
foreach(var item in itemDict){}
这样子是很方便 但我们还是要知道这边var
代表的是键值对KeyValuePair
所以上面那行代码相当于
foreach(KeyValuePair<int, Item> item in itemDict){
Debug.Log(item.Key + " " + item.Value.id + " " + item.Value.name);
}
如果只想获取key或者value
foreach(var key in itemDict.Keys){}
foreach(var value in itemDict.Values){}
The key must be UNIQUE while the values can be whatever u want. And the key must exist.
Dictionary.ContainsKey()/ Dictionary.ContainsValue()
: 判断是否已经有键或者值在里面了(不能用in哦(之前python习惯用in了
if(itemDict.ContainsKey(1)){}
if(itemDict.ContainsValue(sword)){}
When to use dictionary
- Working with large lists: RPG game —>Shop System (执行查询时就不用一直迭代比较 时间复杂度为O(1) (散列表的优势