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


    同样直接上代码:

                List<Student> ss = new List<Student>();
                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("		" + 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()后也很方便,当然这是后话了)。

  • 相关阅读:
    tree related problems (update continuously)
    [单元測试]_[VC2010使用gtest单元測试入门]
    generate alphanumeric serial number
    UiAutomator源代码分析之获取控件信息
    Fckeditor常见漏洞的挖掘与利用整理汇总
    AsyncAwait
    .Net异步编程知多少
    ParameterizedThreadStart task
    AsyncAwait 学习
    8天玩转并行开发——第八天 用VS性能向导解剖你的程序
  • 原文地址:https://www.cnblogs.com/lbhqq/p/8478118.html
Copyright © 2020-2023  润新知