我有一个列表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
非常感谢
答案 0 :(得分:0)
以下代码对您有所帮助,
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"));
}