简体   繁体   中英

Remove item from generic list based on date condition

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)

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));

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)); 

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);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM