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

2021-06-06 23:03

阅读:686

标签:efault   derby   queryable   col   guid   uid   tor   color   star   

1、linq 写的不是很好总结一下

    ①、数据

 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 = new List()
            {
                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" }
            };

  ②、linq

  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;//根据id分成2组【1组里面又包含2组】获取第一组

  ③、lambda

  var lambda = query.OrderByDescending(p => p.time).GroupBy(g => new { g.id, g.time })
                      .GroupBy(g => g.Key.id).FirstOrDefault();

2、第二种

   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;

 

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

标签:efault   derby   queryable   col   guid   uid   tor   color   star   

原文地址:https://www.cnblogs.com/study10000/p/10764083.html


评论


亲,登录后才可以留言!