I have a collection of objects and i need to retreive the ones that were last created for the same type(similar ids). I tried the idea below from an other post but i do not get the expected result. Any other suggestions?
Thanks in advance
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;}
}
Is this what you need?
var group = itemlist1.GroupBy(x=>x.id); // grouped by id
var newList =
group.Select(g => g.OrderByDescending(y => y.Creationdate).First());
it will get most recent items for all ids, by grouping them by ID and then taking only most recent ones from that list and selecting to new list
OrderByDescending
is ordering by date descending so First
is taking most recent date. Select
is selecting expression result to new list, so there should be a list of most recent items for all id's groups
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.