我有一个包含来自单个类的对象集合的列表ListA。这个类由三个属性组成,它们都是字符串:
Code, Ref, StartDate我要创建ListB,确保仅从ListA中选择最新的开始日期
用LINQ做这件事最有效的方法是什么?
来自ListA的示例内容:
OA 001 01.01.2000
OA 001 02.01.2000
OA 001 01.12.2001
OB 002 01.01.2000
ListB中的预期内容:
OA 001 01.12.2001
OB 002 01.01.2000
非常感谢
发布于 2018-04-19 19:57:51
下面的代码会对你有所帮助。
var ListA = new List<Your_Class>() {
new Your_Class{ Code = "OA", Ref ="001",StartDate=Convert.ToDateTime ("01.01.2000")},
new Your_Class{ Code = "OA", Ref ="001",StartDate=Convert.ToDateTime("01.01.2000")},
new Your_Class{ Code = "OA", Ref ="001",StartDate=Convert.ToDateTime("12.01.2001")},
new Your_Class{ Code = "OB", Ref ="002",StartDate=Convert.ToDateTime("01.01.2000")}
};
var ListB = from c in ListA
group c by c.Code into grp
select grp.OrderByDescending(c => c.StartDate).FirstOrDefault();
foreach(Your_Class your_cls in ListB) {
Console.WriteLine(your_cls.Code+" "+your_cls.Ref+" "+ your_cls.StartDate.ToString("dd.MM.yyyy"));
}https://stackoverflow.com/questions/49919524
复制相似问题