• C# linq lambda 分组获取最新的数据


    var id = Guid.Parse("04245059-9251-44e1-4c16-08d6be4a0add");
                Guid id2 = Guid.Parse("12385059-9251-44e1-4c16-08d6be4a0add");
    
                var time = DateTime.Now;
                var time2 = time.AddHours(5);
                List<list_data> list = new List<list_data>()
                {
                    new list_data (){  id=id,name="1三",time=time,flag="sun" },
                    new list_data (){  id=id,name="1四",time=time, flag="moon" },
                    new list_data (){  id=id,name="1五",time=time, flag="star" },
                    new list_data (){  id=id,name="1六",time=time.AddDays(1),flag="moon" },
                    new list_data (){  id=id,name="1七",time=time.AddDays(1),flag="sun" },
                    new list_data (){  id=id,name="1九",time=time.AddDays(1),flag="star" },
                    new list_data (){  id=id2,name="2九",time=time2,flag="sun" },
                    new list_data (){  id=id2,name="2四",time=time2, flag="moon" },
                    new list_data (){  id=id2,name="2五",time=time2, flag="star" },
                    new list_data (){  id=id2,name="2六",time=time2.AddDays(1),flag="moon" },
                    new list_data (){  id=id2,name="2七",time=time2.AddDays(1),flag="sun" },
                    new list_data (){  id=id2,name="2三",time=time2.AddDays(1),flag="star" }
                };
    var query = list.AsQueryable();
                var data = from item in query
                           orderby item.time descending
                           group item by new { item.id ,item.time}
                           into g_data//根据id、time分成4组
                           group g_data by g_data.Key.id into last_data
                           select last_data.FirstOrDefault();//根据id分成2组【1组里面又包含2组】获取第一组
    var lambda = query.OrderByDescending(p => p.time).GroupBy(g => new { g.id, g.time })
                          .GroupBy(g => g.Key.id).Select(p=>p.FirstOrDefault());
    var data2 = from item in query
                            group item by new { item.id, item.flag }
                            into g_data
                            select g_data.OrderByDescending(p => p.time).FirstOrDefault()//根据id、flag分成6组获取每组第一个【凑成一个组】
                            into datas group datas by datas.id//根据id分组分成两组
                            into  last_data select last_data;
    var labmbda2 = query.GroupBy(g => new { g.id, g.flag }).Select(p =>p.OrderByDescending(t=>t.time).FirstOrDefault()).GroupBy(g => g.id);

    来源于这位博主:https://www.cnblogs.com/study10000/p/10764083.html

  • 相关阅读:
    动手动脑2
    假期第五周学习记录
    假期第四周学习记录
    假期第三周学习记录
    假期第二周学习记录
    执行$JAVA_HOME/bin/java -version和java -version命令输出结果不一致
    假期第一周学习记录
    使用VMware创建虚拟机并下载linux系统镜像文件
    VMware Worstation下载安装
    第十七周学习进度
  • 原文地址:https://www.cnblogs.com/Early/p/15875246.html
Copyright © 2020-2023  润新知