繁体   English   中英

根据日期条件从通用列表中删除项目

[英]Remove item from generic list based on date condition

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

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

列表包含ID和日期的项目。 列表中可以包含多个具有相同ID的项目,但ID为1。

假设列表中有3个项目,其中一个项目的ID为2,其余项目的ID为1,则ID为1且最新日期的项目必须位于列表中,其余项目将从列表中删除。

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

我已经尝试过了,但是没有运气。

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

极端:

如果有4个元素(id:1,日期:现在),(id:2,日期:现在),(id:1,日期:昨天),(id:2,日期:昨天)结果将是(id: 1,日期:现在),(id:2,日期:现在),(id:2,日期:昨天)

以下内容将删除每个重复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 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)); 

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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