• QQ群:1040082875


大家好,我是佛系工程师☆恬静的小魔龙☆,不定时更新Unity开发技巧,觉得有用记得一键三连哦。

一、前言

今天分享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<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(FirstValue());
}

private int FirstValue()
{
int value = 0;
foreach (var item in dicTest)
{
value = item.Value;
return value;
}
return value;
}
}

PS:这种写法简单粗暴,在循环中直接返回第一个值,如果没有值就返回0,键值对类型变的时候修改函数即可,比如:

【C#日常】C#集合Dictionary获取第一个键值_开发语言

2-2、使用System.Linq返回第一个键值

引入​​using System.Linq;​​命名空间:

using System.Linq;

使用First()函数就可以返回第一个键值对了:

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

public class TestScripts : MonoBehaviour
{
private Dictionary<string, string> dicTest;

void Start()
{
dicTest = new Dictionary<string, string>();
dicTest.Add("2","13");
dicTest.Add("0","10");
Debug.Log(dicTest.First().Value);
}
}

效果:

【C#日常】C#集合Dictionary获取第一个键值_c#_02

PS:Linq是使用拓展方法,遍历了集合的查询过程,使用简单方便,非常的有用。但是Linq查找的实现过程并不知道,好用是好用,但是对于代码能力的提升并不大。

2-3、使用拓展方法返回第一个键值

我们的第三个方法,就是使用拓展方法,模仿Linq返回第一个键值,参考代码:

拓展方法:

public static KeyValuePair<K, V> First<K, V>(this Dictionary<K, V> dic)
{
KeyValuePair<K, V> dicTemp = new KeyValuePair<K, V>();
if (dic.Count > 0)
{
foreach (var item in dic)
{
dicTemp = item;
return dicTemp;
}
return dicTemp;
}
else
{
return dicTemp;
}
}

调用函数:

using System.Collections.Generic;
using UnityEngine;

public class TestScripts : MonoBehaviour
{
private Dictionary<string, string> dicTest;

void Start()
{
dicTest = new Dictionary<string, string>();
dicTest.Add("2","13");
dicTest.Add("0","10");
Debug.Log(dicTest.First().Value);
}
}

PS:没有使用Linq,但是实现跟Linq一样的效果。

三、总结

今天分享了三种方法返回第一个键值。


  • 使用了循环,返回第一个键值
  • 使用了Linq查询函数,返回第一个键值
  • 使用拓展方法,模仿LInq查询,返回第一个键值

代码不多,不懂的可以加我。