c# - 比较2个队列,找到两个队列中都不存在的元素

标签 c# queue

我目前正在尝试比较 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/

相关文章:

c# - 带有 Mysql 数据库的 asp.net web api

c# - 对数组进行排队还是将 Queue 写入更多维数组?

javascript - 如何在 Node.JS 中限制(或排队)对外部进程的调用?

c - 2个明显相同的代码!一个编译,一个抛出段错误

c# - In 和 Out 属性在 .NET 中如何工作?

c# - .NET Standard 2.0 中的 Microsoft.AspNet.Identity 和 Microsoft.AspNet.Identity.EntityFramework

c# - Linq 嵌套 group by 操作身份数据

c# - 在 Mvc.Controller 中使用服务器

Java:如何添加或创建带有参数的新对象并将其添加到队列中?

php - 我将如何组织数据以向用户发送许多电子邮件?