我目前正在尝试比较 2 个队列。队列中的大多数条目将是重复的(两个队列将具有相同的条目)。我想要做的是,找到两个队列中都不存在的条目。
例如,假设以下是相关的 2 个队列。
1st queue - A S D F G
2nd queue - S A D G Q
条目 A、S、D、G 都存在于两个队列中。然而,条目 F 对于第一个队列是唯一的,而 Q 对于第二个队列是唯一的。我希望能够找出哪些条目是唯一的。有没有一个函数可以做这样的事情?
就这个问题而言,我需要使用队列,因为 FIFO 行为至关重要。
最佳答案
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);
关于c# - 比较2个队列,找到两个队列中都不存在的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33063071/