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

时间:2015-12-14 17:34:18

标签: c# vb.net list

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

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

列表包含具有ID和日期的项目。列表可以包含多个具有相同ID的项目,除了ID 1.

让我们说list有3个项目,其中一个有id 2,其余有id 1,那么id为1,最新日期的项目需要在列表中,其余的将从列表中删除。

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

我试过这个但没有运气。

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

Eaxmple:

如果有4个元素(id:1,Date:Now),(id:2,Date:Now),(id:1,Date:Yesterday),(id:2,Date:Yesterday)结果将是 (id:1,Date:Now),(id:2,Date:Now),(id:2,Date:Yesterday)

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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)); 

答案 2 :(得分:0)

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

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