[U3D Learning Note] Unity C# Survival Guide (15) --Dictionary

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) (散列表的优势
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值