根据日期条件从常规列表中删除项目



如何根据条件从列表中删除项目。

保留列表中的所有项目,但如果文档id为1,则保留最新(最大)日期的项目。

列表包含带有ID和日期的项目。列表中可以有多个id相同的项目,id为1的项目除外。

假设列表有3个项目,其中一个项目id为2,其余项目id为1,则id为1且日期最新的项目需要在列表中,其余项目将从列表中删除。

删除项目后,列表将有两个id为1和2的项目。

我试过了,但没有成功。

var newest = thelist.MaxBy(x => x.DateTimeField);

Eaxmple:

如果有4个元素(id:1,Date:Now(id:1,Date:Now),(id:2,Date:现在),(id:2,Date:昨天)

如果我正确理解你,那么试着使用这样的东西:

var maxDateValue = thelist.Where(x => x.DoctypeID == 1).Max(c => c.DateTimeField);
thelist.RemoveAll(x => x.DoctypeID == 1 & x.DateTimeField != maxDateValue);

更新

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

下面将在每个重复的Id上删除最旧的项。

var res = thelist
            .GroupBy(p => p.Id)
            .SelectMany(grp => grp.Where(pp => grp.Max(item => item.DateTimeField) == pp.DateTimeField));

您也可以使用:

var res = thelist
            .GroupBy(r => r.Id)
            .SelectMany(grp => grp.OrderByDescending(p => p.DateTimeField).Take(1));

找到最长日期,然后删除其他

    var maxDate = thelist.Where(x => x.id == 1).Max(x => x.Date);
    thelist.RemoveAll(x => x.id == 1 && x.Date != maxDate);

最新更新