我有一个对象集合,我需要检索上次为相同类型(类似 id)创建的对象。我从另一篇文章中尝试了下面的想法,但没有得到预期的结果。还有其他建议吗?
提前致谢
void Main()
{
List<data_item> itemlist1= new List<data_item>();
itemlist1.Add(new UserQuery.data_item
{
id=1,
Creationdate = new DateTime(2001, 6, 1),
Size=28373
})
;
itemlist1.Add(new UserQuery.data_item
{
id=2,
Creationdate = new DateTime(1992, 6, 1),
Size=2000
})
;
itemlist1.Add(new UserQuery.data_item
{
id=2,
Creationdate = new DateTime(2002, 6, 1),
Size=300
})
;
itemlist1.Add(new UserQuery.data_item
{
id=1,
Creationdate = new DateTime(2005, 6, 1),
Size =400
})
;
itemlist1.Add(new UserQuery.data_item
{
id=3,
Creationdate = new DateTime(1999, 6, 1),
Size =10000
})
;
itemlist1.Add(new UserQuery.data_item
{
id=3,
Creationdate = new DateTime(2003, 6, 1),
Size =5000
})
;
itemlist1.Add(new UserQuery.data_item
{
id=3,
Creationdate = new DateTime(1999, 4, 1),
Size=3000
})
;
itemlist1.Add(new UserQuery.data_item
{
id=5,
Creationdate = new DateTime(1999, 6, 5),
Size=230
})
;
itemlist1.Add(new UserQuery.data_item
{
id=4,
Creationdate = new DateTime(1999, 6, 1),
Size =8700
})
;
itemlist1.Add(new UserQuery.data_item
{
id=5,
Creationdate = new DateTime(1991, 6, 1),
Size =6000
})
;
itemlist1.Dump();
var result = from t in itemlist1 group t by new UserQuery.data_item
{ id=t.id,
Creationdate=t.Creationdate
} into gt
select gt.OrderByDescending(d=>d.Creationdate).First();
result.Distinct().Dump();
}
// Define other methods and classes here
public class data_item
{
public int id {get;set;}
public DateTime Creationdate {get;set;}
public int? Size {get;set;}
}