linq学习笔记:将List<T> 转换为 Dictionary<T Key,T Value>

运用Linq,将List<T> 转换为 Dictionary<T Key,T Value>

即:List<T>  ToDictionary<T Key,T Value>

 

废话不说,看代码:

示例代码:按照性别分类

class Program
    {
        public class Student
        {
            public string Name { get; set; }
            public int Age { get; set; }
            public int Sex { get; set; }
        }
       
 
        static void Main(string[] args)
        {
            List<Student> lstStudent = new List<Student>();
            lstStudent.Add(new Student { Name = "A1", Age = 17, Sex = 0 });
            lstStudent.Add(new Student { Name = "A2", Age = 19, Sex = 1 });
            lstStudent.Add(new Student { Name = "A3", Age = 17, Sex = 1 });
            lstStudent.Add(new Student { Name = "A4", Age = 19, Sex = 0 });
            lstStudent.Add(new Student { Name = "A5", Age = 18, Sex = 1 });
            lstStudent.Add(new Student { Name = "A6", Age = 18, Sex = 0 });
            lstStudent.Add(new Student { Name = "A7", Age = 18, Sex = 1 });
            lstStudent.Add(new Student { Name = "A8", Age = 19, Sex = 0 });
            lstStudent.Add(new Student { Name = "A9", Age = 19, Sex = 0 });

            var dicStudent = lstStudent.GroupBy(p => p.Sex).ToDictionary(p => p.Key, p => p.ToList());
            foreach (var dic in dicStudent)
            {
                Console.WriteLine("Key:{0}", dic.Key);
                foreach (var stu in dic.Value)
                {
                    Console.WriteLine("Name:{0},Age:{1}", stu.Name, stu.Sex.ToString());
                }
            }
            Console.ReadKey();
        }
    }

实际运行结果:

Key:0
Name:A1,Age:0
Name:A4,Age:0
Name:A6,Age:0
Name:A8,Age:0
Name:A9,Age:0
Key:1
Name:A2,Age:1
Name:A3,Age:1
Name:A5,Age:1
Name:A7,Age:1

 

轻松利用linQ

转载于:https://www.cnblogs.com/CnKker/p/3288554.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值