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);
            }

 

 

 

转载于:https://www.cnblogs.com/tech-bird/p/3634699.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值