随笔 - 146  文章 - 0  评论 - 20  阅读 - 40万

C#经典系列-键值对

1.ToDictionary,ToLookup

从图中我们看到有四个ToXXX的方法,其中ToArray和ToList,用的是非常非常多

我们有这样的一个实体

    class student
    {
        public string StuNo { get; set; } //学号
        public string Grand { get; set; } //年级
        public string Sex { get; set; }   //性别
    }

年级和学号是一对多的关系,也就是说一个年级可能包含几个学号,每个学号都有自己对应的性别

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

        public static List<student> GetList()
        {
            return new List<student>()
            {
                new student(){StuNo="0001",Grand="一年级",Sex=""},
                new student(){StuNo="0002",Grand="二年级",Sex=""},
                new student(){StuNo="0003",Grand="一年级",Sex=""},
                new student(){StuNo="0004",Grand="一年级",Sex=""},
                new student(){StuNo="0005",Grand="二年级",Sex=""},
                new student(){StuNo="0006",Grand="一年级",Sex=""},
                new student(){StuNo="0007",Grand="二年级",Sex=""},
                new student(){StuNo="0008",Grand="一年级",Sex=""},
                new student(){StuNo="0009",Grand="二年级",Sex=""},
                new student(){StuNo="0010",Grand="一年级",Sex=""},
                new student(){StuNo="0011",Grand="三年级",Sex=""},
                new student(){StuNo="0012",Grand="一年级",Sex="人妖"},
                new student(){StuNo="0013",Grand="三年级",Sex=""}
            };
        }
    }
复制代码

这种初始化类对象的方法以及返回方式:

 student  s= new student() { Sex = "nan" };



举个例子: 我需要统计各个年级中的学号情况。

 很明显,这是一个分组排序的问题,可能你马上就想起了groupby来实现,当然groupby是可以实现的,不过groupby不能算是一种数据结构,不能带有索引,没有字典那样容易输出和操作。

方案一: 采用普通的foreach循环。

     一般情况下,可能有一部分人都采用这种原始的方法,将list数据通过foreach循环放到dictionary中,就是代码写的多一些,也算是最灵活的。

复制代码
static void Main(string[] args)
        {
            Dictionary<int, student> dic = new Dictionary<int, student>();
            List<student> stulist = GetList();
            foreach (var item in stulist)
            {
                if (!dic.ContainsKey(item.Grand))
                {
                    dic.Add(item.Grand, item);
                }
                else
                {
                    dic[item.Grand] = item;
                }
            }
            
          
        }
复制代码

结果

方案二:使用ToDictionary

Dictionary是一种键值方式(值是一个对象)

  从图中我们可以看到,发生悲剧的异常了,我们知道dictionary中key是不能重复的,然而ToDictionary中并没有给我们做key的重复值判断,那也就侧面说明ToDictionary在kv中只能是 “一对一”的关系,也就是v中永远只会有一条记录,显然这不是我需要的,在了解ToDictionary原理后,该方案失败。

如果没有重复的

复制代码
class Program
    {
        static void Main(string[] args)
        {
            List<student> stulist = GetList();
            var dic = stulist.ToDictionary(m=>m.Grand);

        }

        public static List<student> GetList()
        {
            return new List<student>()
            {
                new student(){StuNo="0001",Grand=1,Sex=""},
                new student(){StuNo="0002",Grand=2,Sex=""},
                new student(){StuNo="0003",Grand=3,Sex=""},
            };
        }
    }
复制代码

结果是

Dictionary的下标只能是键

方案三: 使用ToLookup(键值对,值是一组对象)

ToDictionary的加强版,可以认为是一种新的字典数据结构,它就避免了这种“一对一”的关系,采用“一对多”的实现。

 

复制代码
static void Main(string[] args)
        {
            var stulist = GetList();
            var dic = stulist.ToLookup(i=>i.Grand);

            foreach (var item in dic)
            {
                Console.WriteLine("年级:" + item.Key);

                foreach (var item1 in item)
                {
                    Console.WriteLine("\t\t" + item1.StuNo + "  " + item1.Sex);
                }
            }
        }
复制代码

结果

 

   而且ToLookup和字典一样,是带有索引形式,这个groupby就不具备了,当然Tolookup还有一个强大的功能,就是使用Func<TSource, TElement> elementSelector来对现在的v元素进行转换来避免刚才  Console.WriteLine("\t\t" + item1.TicketNo + "  " + item1.Description);语句

复制代码
static void Main(string[] args)
        {
            var stulist = GetList();
            var dic = stulist.ToLookup(i => i.Grand, j => { return j.StuNo + "\t" + j.Sex; });

            foreach (var item in dic)
            {
                Console.WriteLine("年级:" + item.Key);

                foreach (var item1 in item)
                {
                    Console.WriteLine("\t\t"+ item1);
                }
            }
        }
复制代码


输出同样的结果

 

 2.键值对集合

 SortedList<TKey, TValue>( )   表示根据键进行排序的键/值对的集合,而键基于的是相关的 IComparer<T> 实现。

SortedDictionary<TKey, TValue>() 表示根据键进行排序的键/值对的集合。

使用KeyValuePair对其进行遍历

复制代码
            SortedList<int, string> sortedList = new SortedList<int, string>();
            foreach (Value val in enumValues)
            {
                sortedList.Add(Convert.ToInt32(val.EnumValueIndex), val.EnumValueName);
            }
        
            foreach (KeyValuePair<int, string> e in sortedList)
            {
                string strName = e.Value;
                SelectListItem myli = new SelectListItem
                {
                    Text = strName,
                    Value = e.Key.ToString(),
                    Selected = (e.Key == value)
                };
                cpType.Add(myli);
            }
复制代码

 

 

 

posted on   飞鸟快跑  阅读(26821)  评论(0)    收藏  举报
编辑推荐:
· Java虚拟机代码是如何一步一步变复杂且难以理解的?
· 领域驱动的事实与谬误 一 DDD 与 MVC
· SQL Server 2025 中的改进
· 当数据爆炸遇上SQL Server:优化策略全链路解析
· 记录一次线上问题排查:JDK序列化问题
阅读排行:
· 一个包含 80+ C#/.NET 编程技巧实战练习开源项目!
· Excel百万数据高性能导出方案!
· 揭秘 AI 工具的系统提示词「GitHub 热点速览」
· DeepWiki:AI驱动、免费且实用的 GitHub 源码阅读与分析神器!
· JavaScript 没有“包”
< 2025年5月 >
27 28 29 30 1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
1 2 3 4 5 6 7

点击右上角即可分享
微信分享提示