c#基础之Dictionary

1、要使用Dictionary集合,需要导入C#泛型命名空间
System.Collections.Generic(程序集:mscorlib)
 

2、描述
1)、从一组键(Key)到一组值(Value)的映射,每一个添加项都是由一个值及其相关连的键组成
2)、任何键都必须是唯一的
3)、键不能为空引用null(VB中的Nothing),若值为引用类型,则可以为空值
4)、Key和Value可以是任何类型(string,int,custom class 等)

 

复制代码
    //创建字典
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(1, "1");

            dic.Add(5, "5");

            dic.Add(3, "3");

            dic.Add(2, "2");

            dic.Add(4, "4");
            //给dic进行排序
            var result = from a in dic orderby a.Key select a;

            //遍历元素
            foreach(KeyValuePair<int,string>pair in result)
            {

                Console.WriteLine("key:'{0}',value:'{1}'",pair.Key,pair.Value);
            }

            //只是遍历键
            Dictionary<int, string>.KeyCollection keyCol = dic.Keys;
            foreach (int key in keyCol)
            {
                Console.WriteLine("Key = {0}", key);
            }
            //只遍历值
            Dictionary<int, string>.ValueCollection valueCol = dic.Values;
            foreach (string value in valueCol)
            {
                Console.WriteLine("Value = {0}", value);
            }
         
            Console.Read();
复制代码

 

复制代码
class Program
    {
        static void Main(string[] args)
        {

            Dictionary<int, List<Test>> tesD = new Dictionary<int, List<Test>>();

            List<Test> tList = new List<Test>();

            for (int i = 0; i <= 5; i++)
            {
                Test t1 = new Test();

                t1.Id = i.ToString() + "i";
                t1.Salary = Convert.ToDecimal(i);

                tList.Add(t1);

                for (int y = 0; y <= 5; y++)
                {
                    Test t = new Test();

                    t.Id = y.ToString() + "Y";
                    t.Salary = Convert.ToDecimal(y);

                    tList.Add(t);
                }
                tesD.Add(i, tList);
            }

            if (tesD.ContainsKey(1))
            {

                List<Test> tt = new List<Test>();

                tt.AddRange(tesD[1]);//赋值给tt


            }
             

            Console.Read();
        }
    }

    public class Test
    {
        public string Id { get; set; }

        public Nullable<decimal> Salary { get; set; }

       


    }
复制代码

 

posted @   安静点--  阅读(446)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示