一、前言
今天分享C#的字典如何返回第一个键值。
首先,分析一下这个需求,如果是输入或者List返回第一个值是很容易的,直接数组[0] 或者List[0],就可以返回第一个值,但是这个在字典中是不适用的。
比如:
using System.Collections.Generic;
using UnityEngine;
public class TestScripts : MonoBehaviour
{
private Dictionary<int, int> dicTest;
void Start()
{
dicTest = new Dictionary<int, int>();
dicTest.Add(2, 13);
dicTest.Add(3, 14);
dicTest.Add(4, 15);
dicTest.Add(0, 11);
dicTest.Add(1, 12);
}
}
这时候的如果Debug.Log(dicTest[0])返回是第4个键值,也就是Key值等于0的键值。
这显然与我们的要求不符,我们需要返回字典中第一个键值。
二、解决方案
2-1、使用循环返回第一个元素
找到第一个元素直接返回值:
using System.Collections.Generic;
using UnityEngine;
public class TestScripts : MonoBehaviour
{
private Dictionary<in