确保两个列表具有相同的元素

时间:2016-08-29 20:47:01

标签: algorithm list math data-structures

我有两个列表,A和B.我想检查A和B,并确保A只包含B包含的元素。 示例:在A = {1,2,3,4}中,B = {3,4,5,6}。最后,我希望A为{3,4,5,6}。 条件:我不想完全用B替换A而且我不想改变B.

public void setA(List B)
{
   foreach(x in B)
   {
      if(!A.Contains(x))
           A.Add(x)
   }
   foreach(x in A)
   {
      if(!B.Contains(x))
          A.Delete(x)
   }
} 

有没有更好的方法呢? (可能是单循环或甚至更好)

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

var listATest = new List<int>() { 1, 2, 3, 4, 34, 3, 2 };
var listBTest = new List<int>() { 3, 4, 5, 6 };

// Make sure listATest is no longer than listBTest first
while (listATest.Count > listBTest.Count)
{
    // Remove from end; as I understand it, remove from beginning is O(n)
    // and remove from end is O(1) in Microsoft's implementation
    // See http://stackoverflow.com/questions/1433307/speed-of-c-sharp-lists
    listATest.RemoveAt(listATest.Count - 1);
}

for (int i = 0; i < listBTest.Count; i++)
{
    // Handle the case where the listATest is shorter than listBTest
    if (i >= listATest.Count)
        listATest.Add(listBTest[i]);

    // Make sure that the items are different before doing the copy
    else if (listATest[i] != listBTest[i])
        listATest[i] = listBTest[i];
}