C# Dictionary 遍历 -- Unity

本文介绍了一种使用C#实现的学生信息管理类,通过Dictionary存储学生信息,并提供了五种不同的遍历方法,包括直接遍历、使用KeyValuePair、遍历Keys、先将Keys转换为List再遍历及仅遍历Values。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

/// <summary>
///  C# Dictionary 语法测试
///  遍历容器
/// </summary>
public class Dictionary_Test
{
    private class StudentInfo
    {
        public StudentInfo(int num, string na, int ag, float he)
        {
            number = num;
            name = na;
            age = ag;
            height = he;
        }

        public override string ToString()
        {
            return string.Format("number = {0},name = {1},age = {2},height = {3}", number, name, age, height);
        }

        public int number;
        public string name;
        public int age;
        public float height;
    }

    private Dictionary<int, StudentInfo> studentInfos;

    public Dictionary_Test()
    {
        /// 赋值,初始化
        studentInfos = new Dictionary<int, StudentInfo>();
        for (int i = 0; i < 5; ++i)
        {
            int number = 1000 + i;
            StudentInfo info = new StudentInfo(number, "Ab_" + i.ToString(), i + 10, 1.7f);
            studentInfos.Add(number, info);
        }
    }

    /// <summary>
    /// C# Dictionary 遍历
    /// </summary>
    public void TraverseContainer()
    {
        /// 遍历方法1
        foreach (var item in studentInfos)
        {
            /// unity环境中的输出
            Debug.Log(string.Format("遍历方法1:number = {0},StudentInfo = ({1})", item.Key, item.Value));
        }

        /// 遍历方法2
        foreach (KeyValuePair<int, StudentInfo> keyPair in studentInfos)
        {
            /// unity环境中的输出
            Debug.Log(string.Format("遍历方法2:number = {0},StudentInfo = ({1})", keyPair.Key, keyPair.Value));
        }

        /// 遍历方法3
        foreach (int key in studentInfos.Keys)
        {
            /// unity环境中的输出
            Debug.Log(string.Format("遍历方法3:number = {0},StudentInfo = ({1})", key, studentInfos[key]));
        }

        /// 遍历方法4
        List<int> keys = new List<int>(studentInfos.Keys);
        for (int i = 0, count = keys.Count; i < count; ++i)
        {
            int key = keys[i];
            /// unity环境中的输出
            Debug.Log(string.Format("遍历方法4:number = {0},StudentInfo = ({1})", key, studentInfos[key]));
        }

        /// 遍历方法5
        foreach (StudentInfo value in studentInfos.Values)
        {
            /// unity环境中的输出
            Debug.Log(string.Format("遍历方法5:StudentInfo = ({0})", value));
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值