C#-字典(Dictionary)用法
目录
字典(Dictionary)是一种非常有用的数据结构,它存储键值对(key-value pairs)。字典中的每个键都是唯一的,并且每个键都是唯一的,并且每个键映射到一个值。字典提供了快速的查找、添加和删除键值对的能力。
namespace demo
{
internal class Program
{
static void Main(string[] args)
{
// 1.字典初始化
Dictionary<int, string> dict = new Dictionary<int, string>();
dict = new Dictionary<int, string>()
{
{1, "Value1"},
{2, "Value2"},
{3, "Value3"},
{4, "Value4"},
{5, "Value5"}
};
// 添加元素
dict.Add(6, "Value6");
dict.Add(7, "Value7");
dict.Add(8, "Value8");
dict.Add(9, "Value9");
// 2.列表与字典转换
List<string> DataListA = new List<string> { "A", "B", "C", "D", "E", "F" };
List<int> DataListB = new List<int> { 100, 200, 300, 400, 500, 600 };
// 列表转换为字典
dict = ListToDictionary(DataListA);
dict = ListToDictionary(DataListB);
// 将字典转换为列表
DataListA = DictionaryToList(dict);
// 3.字典遍历、查找、删除
// 通过KeyValuePair遍历字典
foreach (KeyValuePair<int, string> keyValuePair in dict)
{
Console.WriteLine($"Key: {keyValuePair.Key}, Value: {keyValuePair.Value}");
}
// 通过Key查找元素
if (dict.ContainsKey(3))
{
string v1 = dict[3];
Console.WriteLine("Key:{0}, Value:{1}", "3", dict[3]);
}
// 通过Remove 方法移除指定的键值
if (dict.ContainsKey(1))
{
Console.WriteLine("Key:{0},Value:{1}", "1", dict[1]);
dict.Remove(1);
}
else
{
Console.WriteLine("不存在 Key : 1");
}
}
/// <summary>
/// 将字典转换为列表
/// </summary>
public static List<string> DictionaryToList(Dictionary<int, string> dict)
{
List<string> RetList = new List<string>();
// 通过KeyValuePair遍历字典
foreach (KeyValuePair<int, string> keyValuePair in dict)
{
RetList.Add(keyValuePair.Value);
}
return RetList;
}
/// <summary>
/// 将列表转换为字典
/// </summary>
/// <param name="DataList">字符串列表</param>
public static Dictionary<int, string> ListToDictionary(List<string> DataList)
{
Dictionary<int, string> RetDic = new Dictionary<int, string>();
for (int i = 0; i < DataList.Count; i++)
{
RetDic.Add(i, DataList[i]);
}
return RetDic;
}
/// <summary>
/// 将列表转换为字典
/// </summary>
public static Dictionary<int, string> ListToDictionary(List<int> DataList)
{
Dictionary<int, string> RetDic = new Dictionary<int, string>();
for (int i = 0; i < DataList.Count; i++)
{
RetDic.Add(i + 1, DataList[i].ToString());
}
return RetDic;
}
}
}