【问题标题】:Checking items in two lists检查两个列表中的项目
【发布时间】:2014-01-27 08:11:03
【问题描述】:

我在尝试检查两个列表中的重复项时遇到了一些问题。我要做的是检查 distSPUItem 是否在 prodSubstitute 列表中包含 ID,然后执行某些操作。代码如下:

    List<ProductPacking> prodSubstitute = new List<ProductPacking>();
    List<DistributionStandardPackingUnitItems> distSPUItem = new List<DistributionStandardPackingUnitItems>();
    for (int count = 0; count < prodSubstitute.Count; count++)
        {
             if (!distSPUItem.Contains(prodSubstitute[count].id))
             {
                //Perform something here
             }
        }

但是它告诉我最好的重载方法。包含的参数无效。任何指南?提前致谢。

【问题讨论】:

  • 这不是完整的错误信息。最好的超载是什么?
  • 它标记了哪种方法?

标签: c# asp.net list


【解决方案1】:

您的列表 distSPUItem 仅包含 DistributionStandardPackingUnitItems 类型的对象,但是您正在检查列表是否包含 int 变量(您的 ID)。在 .Contains 方法中,您还需要传递 DistributionStandardPackingUnitItems 类型的对象。

如果你只想检查ID,你可以使用LINQ

if(!distSPUItem.Any(i => i.ID == prodSubstitute[count].id))
{
    // perform something here
}

【讨论】:

    【解决方案2】:

    试试这个,

    List<ProductPacking> prodSubstitute = new List<ProductPacking>();
        List<DistributionStandardPackingUnitItems> distSPUItem = newList<DistributionStandardPackingUnitItems>();
    
                    var q = prodSubstitute.Where(item => distSPUItem.Select(item2 => item2).Contains(item));
                    var y = prodSubstitute .Except(distSPUItem ); // y will have 2, since 2 are not included in list2
    
                    foreach (var i in q)
                    {
                       //Perform something here
                    }
    

    【讨论】:

      【解决方案3】:

      为了获得最佳性能,您可以在 id 键上加入两个列表并检查是否为空。

      var q = from p in prodSubstitute
              join d in distSPUItem on p.id equals d.id into g
              from x in g.DefaultIfEmpty()
              where x == null
              select p;
      
      foreach(var item in q)
      {
         //Perform something here
      }
      

      【讨论】:

      • 是的,它可以工作,但与上面的答案相比,它有点复杂。非常感谢
      • @Gwen 是的,但 join 的查找时间为 O(1),而 Any 的查找时间为 O(N)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      • 1970-01-01
      • 2014-06-25
      • 1970-01-01
      • 2010-09-20
      相关资源
      最近更新 更多