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