Linq分组取分组中的最大值,并且拿到最大值对应的id
List<PhoneCallCTIPushData> phoneCallCTIPushDatas = new List<PhoneCallCTIPushData>(); PhoneCallCTIPushData phoneCallCTIPushData1 = new PhoneCallCTIPushData() { }; phoneCallCTIPushData1.Id = 119; phoneCallCTIPushData1.MobilePhoneNum = "13059310001"; phoneCallCTIPushData1.CreateDate = Convert.ToDateTime("2022-10-01"); phoneCallCTIPushDatas.Add(phoneCallCTIPushData1); PhoneCallCTIPushData phoneCallCTIPushData2 = new PhoneCallCTIPushData() { }; phoneCallCTIPushData2.Id = 1299; phoneCallCTIPushData2.MobilePhoneNum = "13059310001"; phoneCallCTIPushData2.CreateDate = Convert.ToDateTime("2022-11-02"); phoneCallCTIPushDatas.Add(phoneCallCTIPushData2); PhoneCallCTIPushData phoneCallCTIPushData13 = new PhoneCallCTIPushData() { }; phoneCallCTIPushData13.Id = 99; phoneCallCTIPushData13.MobilePhoneNum = "13059310001"; phoneCallCTIPushData13.CreateDate = Convert.ToDateTime("2022-12-02"); phoneCallCTIPushDatas.Add(phoneCallCTIPushData13); PhoneCallCTIPushData phoneCallCTIPushData3 = new PhoneCallCTIPushData() { }; phoneCallCTIPushData3.Id = 3; phoneCallCTIPushData3.MobilePhoneNum = "13059310002"; phoneCallCTIPushData3.CreateDate = Convert.ToDateTime("2022-10-03"); phoneCallCTIPushDatas.Add(phoneCallCTIPushData3); PhoneCallCTIPushData phoneCallCTIPushData4 = new PhoneCallCTIPushData() { }; phoneCallCTIPushData4.Id = 4; phoneCallCTIPushData4.MobilePhoneNum = "13059310002"; phoneCallCTIPushData4.CreateDate = Convert.ToDateTime("2022-10-04"); phoneCallCTIPushDatas.Add(phoneCallCTIPushData4); //第一轮筛选:筛选出最新日期的手机号对应的数据 var linqResult = from t1 in phoneCallCTIPushDatas group t1 by t1.MobilePhoneNum into groupTable select new { CreateDate2 = groupTable.Max(x => x.CreateDate), MobilePhoneNum2 = groupTable.Key }; List<PhoneCallCTIPushData> phoneCallCTIPushDatas2 = new List<PhoneCallCTIPushData>(); Console.WriteLine("打印准备要筛选的:"); foreach (var item in linqResult) { //第二轮筛选:匹配最新日期的手机号对应的id值 PhoneCallCTIPushData phoneCallCTIPushData = phoneCallCTIPushDatas.Where(aa => aa.CreateDate == item.CreateDate2 && aa.MobilePhoneNum == item.MobilePhoneNum2).FirstOrDefault(); phoneCallCTIPushDatas2.Add(phoneCallCTIPushData); Console.WriteLine(item.CreateDate2 + " " + item.MobilePhoneNum2 + " "); } Console.WriteLine(); Console.WriteLine("打印结果:"); foreach (var item in phoneCallCTIPushDatas2) { Console.WriteLine(item.Id + " " + item.MobilePhoneNum + " " + item.CreateDate); } Console.ReadKey();
搜索
复制
标签:MobilePhoneNum,最大值,Linq,item,分组,phoneCallCTIPushDatas,new,CreateDate,PhoneCallCT From: https://www.cnblogs.com/jankie1122/p/16808889.html