【问题标题】:Using .Where clause and conditional to Filter Array使用 .Where 子句和条件过滤数组
【发布时间】:2018-05-03 16:50:53
【问题描述】:

我有 2 个 IEnumerable 列表,它们有一个名为 GetId() 的方法,它返回一个 integer

IEnumerable oldBoats
IEnumerable updatedBoats

我想比较两个列表。如果updatedBoats.getId()oldBoats 相比返回一个唯一的ID,我想将它添加到列表中。

所以我这样做了:

IEnumerable<Boat> newBoats = updatedBoats
    .Where(c => oldBoats
    .Any(d => d.GetId() != c.GetId())
    .ToList()

oldBoatsnewBoats 的当前 ID 是 [1, 2, 3, 4, 5]。我想测试基本情况,但这没有通过。当newBoats 应该返回none 时,它总是返回所有ID 的列表。我对cd 的排序是不是错了?

【问题讨论】:

  • Where 不返回 bool。您的内部Where 可能是Any
  • @MikeMcCaughan 谢谢我更新了问题,但我仍然返回所有整数
  • 你的问题没有意义,你说If newBoats.getId() returns a unique Id,你能解释清楚吗?
  • 我会尝试使用 Select 从 oldBoats 获取 id,然后在 updatedBoats 上的 where 以检查 id 中没有的内容
  • 请向我们提供GetId() 的代码,以及运行该代码时updatedBoats 中的内容。

标签: c# filter where


【解决方案1】:

这个怎么样?

var newBoats = updatedBoats.Where(u => !oldBoats.Any(o => o.GetId() == u.GetId()));

【讨论】:

    【解决方案2】:

    这段代码的作用

    IEnumerable<Boat> newBoats = updatedBoats.Where(c=> oldBoats.Any(d =>d.GetId() != c.GetId()).ToList()
    

    大致翻译为:“给我所有更新的船,其 ID 与至少一个旧船 ID 不匹配”。那不是你想要的。您想要的逻辑是“给我所有 ID 与任何旧船 ID 都不匹配的更新船”,这由 @zeroef 正确指定:

    var newBoats = updatedBoats.Where(u => !oldBoats.Any(o => o.GetId() == u.GetId()));  
    // This is O(o * n) for # of old boats * # of updates that are new boats, and something like O((o/2)*n) for # of old boats * number of updated old boats
    

    也就是说,请注意我的评论。这将使用HashSet&lt;T&gt; 更有效地实现:

    // This is O(n) for # of updated boats
    var newBoatIds = new HashSet<Int32>(updatedBoats.Select(b => b.GetId())); 
    // This is O(n) for # of old boats
    newBoatIds.ExceptWith(oldBoats.Select(b => b.GetId()));
    

    这显着减少了嵌套迭代的次数,如果您有很多船(特别是如果您的更新中有很多新船),您会看到差异。

    HashSet 方法适用于 ID,但如果您在使用 ID 进行比较的 Boat 类上实现 Equals() 和 GetHashcode(),您也可以使其适用于实体本身。

    【讨论】:

      猜你喜欢
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-06
      • 1970-01-01
      • 1970-01-01
      • 2021-08-01
      相关资源
      最近更新 更多