C# Dictionary 遍历

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ZFSR05255134/article/details/53184339
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));
        }
    }
}

猜你喜欢

转载自blog.csdn.net/ZFSR05255134/article/details/53184339