在C#中,字典(Dictionary)是一种非常有用的数据结构,它存储键值对(key-value pairs)。字典中的每个键都是唯一的,并且每个键映射到一个值。字典提供了快速的查找、添加和删除键值对的能力。private static void Main(){ Dictionary<int, string> DicList = new Dictionary<int, string>();
DicList = new Dictionary<int, string>() { {1, "Value1"}, {2, "Value2"}, {3, "Value3"}, {4, "Value4"}, {5, "Value5"} };
DicList.Add(6, "Value6"); DicList.Add(7, "Value7"); DicList.Add(8, "Value8"); DicList.Add(9, "Value9");
List<string> DataListA = new List<string> { "A", "B", "C", "D", "E", "F" }; List<int> DataListB = new List<int> { 100, 200, 300, 400, 500, 600 };
DicList = DictionaryHelper.Handle.ListToDictionary(DataListA);
DicList = DictionaryHelper.Handle.ListToDictionary(DataListB);
DataListA = DictionaryHelper.Handle.DictionaryToList(DicList);
foreach (KeyValuePair<int, string> kvp in DicList) { Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); }
if (DicList.ContainsKey(3)) { var v1 = DicList[3]; Console.WriteLine("Key:{0},Value:{1}", "3", DicList[3]); }
if (DicList.ContainsKey(1)) { Console.WriteLine("Key:{0},Value:{1}", "1", DicList[1]); DicList.Remove(1); } else { Console.WriteLine("不存在 Key : 1"); }
}
public List<string> DictionaryToList(Dictionary<int, string> dic){ List<string> RetList = new List<string>();
foreach (KeyValuePair<int, string> kvp in dic) { RetList.Add(kvp.Value); } return RetList;}
public 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 + 1, DataList[i]); } return RetDic;}
public 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;}
阅读原文:原文链接
该文章在 2025/7/9 9:14:52 编辑过