2015-10-11 83 views
2

我正在尝试比较2个队列。队列中的大部分条目将重复(两个队列将具有相同的条目)。我希望能够做到的是,找到两个队列中不存在的条目。比较2个队列并查找两个队列中不存在的元素

例如,假设以下是有问题的2个队列。

1st queue - A S D F G 
2nd queue - S A D G Q 

条目A,S,D,G存在于两个队列中。但是,条目F对于第一个队列是唯一的,对于第二个队列而言,Q是唯一的。我希望能够找出哪些条目是唯一的。有没有这样的功能?

为了这个问题,我需要使用一个队列,因为FIFO行为是至关重要的。

+1

遍历第一队列,并检查是否使用含有() – Mathias

+0

类似的问题在第二队列存在的当前值:http://stackoverflow.com/questions/15111698/comparing-two-lists-for -c-sharp-and-the-of-the-in-c-sharp和http://stackoverflow.com/questions/15111698/comparing-two-lists-for-duplicates-in-either-of-them-in-c -sharp – NoChance

+0

@dwnenr由于我的[post](http://stackoverflow.com/a/33063345/3110834)回答**比较2个队列并找到两个队列中都不存在的元素**,我认为它会对未来的读者更有用,如果你接受答案:) –

回答

1
var firstQueue = new Queue<char>() {}; 
var secondQueue = new Queue<char>() {}; 

foreach (char obj in firstQueue) 
{ 
    if (!secondQueue.Contains(obj)) 
    { 
     // Doesn't exist in the second queue -> Do something 
    } 
} 

做的更短的方法是使用LINQ:

// Will contain all the values that secondQueue doesn't contain. 
var exampleOne = firstQueue.Except(secondQueue); 

// Will contain all the values that firstQueue doesn't contain. 
var exampleTwo = secondQueue.Except(firstQueue); 

// Will contain all the values that both queues have in common. 
var exampleThree = firstQueue.Intersect(secondQueue); 
0

将打印不匹配到控制台窗口中的元素。您也可以将它们保存到列表或数组中。

using System; 
using System.Collections; 
using System.Collections.Generic; 


public class QueueDemo 
{ 
    public static void Main(String[] args) 
    { 
     List<char> list1 = new List<char>{'A', 'S', 'D', 'F', 'G' }; 
     Queue<char> Q1 = new Queue<char>(list1); 

     List<char> list2 = new List<char>{'S', 'A', 'D', 'G', 'Q' }; 
     Queue<char> Q2 = new Queue<char>(list2); 

     foreach (char e in Q1) 
     { 
      if (!Q2.Contains(e)) 
      { 
       Console.WriteLine(e); 
      } 
     } 

     foreach (char e in Q2) 
     { 
      if (!Q1.Contains(e)) 
      { 
       Console.WriteLine(e); 
      } 
     } 

    } 
}