Reputation: 3157
How to remove an item from the list based on condition.
Keep all the items in the list but if doc id is 1 then keep the one with latest (max) date.
List contains items with ID's and dates. List can have multiple items with same ids except id 1.
Lets say list has 3 items one of them has id 2 and the rest has id 1 then the item with id 1 with latest date needs to be in the list and rest will be removed from the list.
After removing item list will have two items with id 1 and 2.
I have tried this but no luck.
var newest = thelist.MaxBy(x => x.DateTimeField);
Eaxmple:
if there are 4 elements (id: 1, Date: Now), (id: 2, Date: Now), (id: 1, Date: Yesterday), (id: 2, Date: Yesterday) results will be (id: 1, Date: Now), (id: 2, Date: Now),(id: 2, Date: Yesterday)
Upvotes: 1
Views: 2168
Reputation: 24619
If I understood you properly then try to use something like that:
var maxDateValue = thelist.Where(x => x.DoctypeID == 1).Max(c => c.DateTimeField);
thelist.RemoveAll(x => x.DoctypeID == 1 & x.DateTimeField != maxDateValue);
UPDATE
var idValue = 1; //to prevent the use of magic numbers
IList<yourType> filteredList = new List(thelist.Where(x => x.DoctypeID == idValue ));
var maxDateValue = filteredList.Max(c => c.DateTimeField);
thelist.RemoveAll(filteredList.Where(x.DateTimeField != maxDateValue));
Upvotes: 2
Reputation: 5488
Find the max date and then remove else
var maxDate = thelist.Where(x => x.id == 1).Max(x => x.Date);
thelist.RemoveAll(x => x.id == 1 && x.Date != maxDate);
Upvotes: 0
Reputation: 12196
The following will remove on every duplicate Id the oldest items.
var res = thelist
.GroupBy(p => p.Id)
.SelectMany(grp => grp.Where(pp => grp.Max(item => item.DateTimeField) == pp.DateTimeField));
You can also use:
var res = thelist
.GroupBy(r => r.Id)
.SelectMany(grp => grp.OrderByDescending(p => p.DateTimeField).Take(1));
Upvotes: 1