2

I'm currently trying to compare 2 queues. Most of the entries in the queue will be duplicate (both queues will have the same entries). What I want to be able to do is, find an entry that does not exist in both queues.

For example, assuming the following are the 2 queues in question.

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

The entry A, S, D, G exists in both queue. However, the entry F is unique for the 1st queue, and Q is unique for the 2nd queue. I want to be able to find out which entries are unique. Is there a function that does something like this?

For the sake of the question, I need to use a queue as the FIFO behavior is crucial.

dwnenr
  • 443
  • 1
  • 4
  • 15
  • 1
    Loop over the 1st queue and check if the current value exists in the 2nd queue using contains() –  Oct 11 '15 at 08:42
  • Similar question to: http://stackoverflow.com/questions/15111698/comparing-two-lists-for-duplicates-in-either-of-them-in-c-sharp and http://stackoverflow.com/questions/15111698/comparing-two-lists-for-duplicates-in-either-of-them-in-c-sharp – NoChance Oct 11 '15 at 08:43
  • @dwnenr Since my [post](http://stackoverflow.com/a/33063345/3110834) answers **Comparing 2 queues and finding an element that does not exist in both queues**, I think it will be more useful for future readers if you kindly accept the answer :) – Reza Aghaei Nov 04 '15 at 10:10

2 Answers2

2
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
    }
}

A shorter way of doing it is using 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

Will print the elements not matching to the console window. You can save them to a list or Array as well.

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);
            }
        }

    }
}
Abdullah Leghari
  • 2,332
  • 3
  • 24
  • 40