unity 字典用法

添加:Dic.Add(key,value);//给字典添加值

删除:Dic.Remove(key);//删除指定值

访问:Dic[key]//表示key所对应的值

判断空:Dic.ContainsKey(key)//判断key是否存在

修改字典的值
   Dictionary<CollectSwitch, bool> collectSwitchValue = new Dictionary<CollectSwitch, bool>();

   
//重置字典所有数值
 public void ResetEvent() 
    {
        List<CollectSwitch> collectSwitches = new List<CollectSwitch>(collectSwitchValue.Keys);
        for (int i = 0; i < collectSwitches.Count; i++)
        {
            collectSwitchValue[collectSwitches[i]] = false;
            Debug.Log($"{collectSwitches[i]}  {collectSwitchValue[collectSwitches[i]]}");
        }
    }

//在不确定key值是否存在的情况下,
//使用字典(Dictionary)的TryGetValue()方法来判断指定键是否存在,如:
    int val;
    if (dic.TryGetValue(key, out val))
    {
        //如果指定的字典的键存在
        dic[key] = newValue;
    }
    else
    {
        //不存在,则添加
        dic.Add(key, newValue);
    }

//还可以使用LINQ来访问字典的键并修改对应的值,如:
Dictionary<string, int> dict = new Dictionary<string, int>();
dict = dict.ToDictionary(x => x.Key, x => x.Value + 1);

### Unity C# 字典遍历示例 在 Unity 使用 C# 进行开发时,字典(`Dictionary<TKey, TValue>`)是一种常用的数据结构。下面展示了一个简单的例子来说明如何创建和遍历字典。 ```csharp using UnityEngine; using System.Collections.Generic; public class DictionaryIterationExample : MonoBehaviour { void Start() { // 创建一个新的字符串到整数的字典 Dictionary<string, int> ageOfPeople = new Dictionary<string, int>(); // 添加键值对至字典中 ageOfPeople.Add("Alice", 30); ageOfPeople.Add("Bob", 25); ageOfPeople.Add("Charlie", 35); // 方法一:使用foreach循环迭代字典中的每一对键值 foreach (KeyValuePair<string, int> entry in ageOfPeople) { Debug.Log($"Name: {entry.Key}, Age: {entry.Value}"); } // 方法二:仅获取所有的键或值并进行迭代 foreach (string name in ageOfPeople.Keys) { Debug.Log($"Person Name: {name}"); } foreach (int age in ageOfPeople.Values) { Debug.Log($"Age: {age}"); } } } ``` 这段代码展示了两种不同的方式来遍历 `Dictionary<string, int>` 类型的对象。一种是通过枚举每一个完整的键值对;另一种则是分别处理所有的键或者所有的值[^1]。 对于更复杂的操作,比如根据特定条件筛选数据项,则可以利用 LINQ 查询表达式来进行更加灵活的操作[^5]: ```csharp // 假设我们想要找出年龄大于等于30岁的人的名字列表 var namesOverThirty = from pair in ageOfPeople where pair.Value >= 30 select pair.Key; foreach (string name in namesOverThirty) { Debug.Log(name); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值