【问题标题】:Remove item from generic list based on date condition根据日期条件从通用列表中删除项目
【发布时间】:2015-12-15 02:57:38
【问题描述】:

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

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

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

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

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

我试过了,但没有运气。

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

示例:

如果有 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)

【问题讨论】:

  • 可能我需要在 x.DoctypeID = 1 的地方添加条件?
  • 为什么要加两个标签C#vb.net
  • 首先你说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 是不是唯一的?
  • 这将为 c# 和 vb.net 专家提供机会来回答这个问题,因为我同时使用这两种语言。
  • @Plutonix; 1 是唯一的,因为它们不能有相同的日期。

标签: c# vb.net list


【解决方案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)); 

【讨论】:

  • 感谢您的回答,关于 max 函数的快速问题。我可以将它用于整数字段吗?
  • 是的,当然。我会在几分钟内尝试改进代码,因为它不是很好:)
  • @user1263981 我对代码进行了一些重构。请看
【解决方案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));

【讨论】:

  • 我想保留列表中的所有项目,但如果 doc id 为 1,则保留最新(最大)日期的项目。
【解决方案3】:

找到最大日期,然后删除 else

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

【讨论】:

  • 我想要(id: 1, Date: Now), (id: 2, Date: Now) and (id: 2, Date: Yesterday)
  • 条件假设适用于 doc id = 1 的项目
  • @user1263981 更新后删除所有功能
猜你喜欢
  • 2011-03-17
  • 1970-01-01
  • 2014-09-22
  • 1970-01-01
  • 1970-01-01
  • 2015-08-11
  • 1970-01-01
相关资源
最近更新 更多