c# 中Linq Lambda 的ToLookup方法的使用

2021-02-12 09:18

阅读:645

同样直接上代码:

            List ss = new List();
            Student ss1 = new Student() { Id = 1, Age = 1, Name = "11" };
            Student ss2 = new Student() { Id = 1, Age = 1, Name = "11" };
            Student ss3 = new Student() { Id = 2, Age = 2, Name = "22" };
            Student ss4 = new Student() { Id = 2, Age = 2, Name = "22" };
            Student ss5 = new Student() { Id = 2, Age = 2, Name = "22" };
            Student ss6 = new Student() { Id = 3, Age = 3, Name = "33" };
            ss.Add(ss1);
            ss.Add(ss2);
            ss.Add(ss3);
            ss.Add(ss4);
            ss.Add(ss5);
            ss.Add(ss6);
            //var aa = ss.GroupBy(m => new { m.Id, m.Age }).Select(group => new {group.Key.Id,group.Key.Age,count = group.Count()}).ToList();
            //foreach (var item in aa)
            //{
            //    Console.WriteLine(item.Id + "||" + item.Age + "||" + item.count);
            //}

            var dic = ss.ToLookup(m => m.Id);
            foreach (var item in dic)
            {
                Console.WriteLine("学生ID号:" + item.Key);

                foreach (var item1 in item)
                {
                    Console.WriteLine("\t\t" + item1 + " || " + item1.Age + " || " + item1.Name);
                }
            }

执行结果:

学生ID号:1
                Test.Student || 1 || 11
                Test.Student || 1 || 11
学生ID号:2
                Test.Student || 2 || 22
                Test.Student || 2 || 22
                Test.Student || 2 || 22
学生ID号:3
                Test.Student || 3 || 33

 

其中item1是student实例。

此方法的作用和ToDictionary类似,但避免Dictionary类型key子段不能重复的问题。

同时也可用于按某字段Group By排序的场景,且相对后者的优势是带有索引便于操作(其实Group By的数据后面添加ToList()后也很方便,当然这是后话了)。

 


评论


亲,登录后才可以留言!