zoukankan      html  css  js  c++  java
  • 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()后也很方便,当然这是后话了)。

  • 相关阅读:
    从PubMed的HTML页面提取标题和摘要文本
    PDB(Protein Data Bank)数据格式详解
    Python+webdriver单选框/复选框定位
    Python+webdriver下拉菜单及鼠标悬浮菜单定位
    Python+webdriver切换iframe/frame
    Python+webdriver自动化脚本弹出框定位
    Python+webdriver脚本之多窗口切换新解
    python杂记
    Python+webdriver定位元素的几种方法
    Python函数
  • 原文地址:https://www.cnblogs.com/lbhqq/p/8478118.html
Copyright © 2011-2022 走看看