zoukankan      html  css  js  c++  java
  • 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("		" + item1.StuNo + "  " + item1.Sex);
                    }
                }
            }

    结果

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

    static void Main(string[] args)
            {
                var stulist = GetList();
                var dic = stulist.ToLookup(i => i.Grand, j => { return j.StuNo + "	" + j.Sex; });
    
                foreach (var item in dic)
                {
                    Console.WriteLine("年级:" + item.Key);
    
                    foreach (var item1 in item)
                    {
                        Console.WriteLine("		"+ 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);
                }
  • 相关阅读:
    子组件 调用父组件方法
    加载进度条
    form 验证 自定义
    关于读取本地text文件,自动被添加空格的问题
    关于form表单中button按钮自动提交问题
    正态分布折线图/直方图相关方法以及概念
    大于0的数字(包含小数和整数)的正则表达式
    bigdecimal类型除法问题
    添加数据库的Maven依赖(SqlServer,Oracle)
    JS中null与undefined的区别
  • 原文地址:https://www.cnblogs.com/tech-bird/p/3634699.html
Copyright © 2011-2022 走看看