【问题标题】:Implementing an intersection merge of 2 array lists实现 2 个数组列表的交集合并
【发布时间】:2013-06-09 12:00:00
【问题描述】:

对于家庭作业,我们必须编写 2 个 ArrayList 的交叉合并。我已经使用以下代码完成了它

    public void Intersection()
    {
        foreach (object obj1 in Developed)
        {
            Apps xApp = (Apps)obj1;
            foreach (object obj2 in DPloyed)
            {
                Apps yApp = (Apps)obj2;
                if (xApp.CompareName(yApp) == 0)
                {
                    Inter.Add(yApp);
                }
            }
        }

    }

我想使用 while 循环来实现它,但下面的代码似乎在列表中保留了缺失的元素。它将第一个元素放入新的交集列表中,但是一旦开发的长度从 1 个元素增加到 5 个元素或更多,它就不会添加新元素。

    public void Intersection()
    {
        int i = 0;
        int j = 0;
        while (i < Developed.Count && j < DPloyed.Count)
        {
            Apps curA = (Apps)Developed[i];
            Apps curB = (Apps)DPloyed[j];
            if (curA.CompareName(curB) == 0)
            {
                Inter.Add(curA);
                i++;
                j++;
            }
            else if (curA.CompareName(curB) < 0)
            {
                i++;
            }
            else
                j++;
        }
    }

任何关于为什么 while 循环不起作用的帮助将不胜感激。

谢谢

【问题讨论】:

    标签: c# merge


    【解决方案1】:

    这样做

    while (i < Developed.Count || j < DPloyed.Count)
    

    因为可能两个列表可能有不同的计数。

    并且您需要在循环内对索引进行额外检查,以免获得Index out of Range Exception

    【讨论】:

    • Give me an argument is out of range exception was unhandled error on my Develop[i]
    • 我是否应该在我的交集方法中实现一个额外的 while 循环来处理一个列表是否已完成处理而另一个列表未完成?
    • 好的。我会看看我能想出什么。谢谢。
    【解决方案2】:

    问题不在合并的实际代码中。在我的比较方法中发现问题。

    【讨论】:

      猜你喜欢
      • 2012-03-25
      • 1970-01-01
      • 1970-01-01
      • 2014-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-12
      相关资源
      最近更新 更多