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.

3
  • 1
    Loop over the 1st queue and check if the current value exists in the 2nd queue using contains() Commented Oct 11, 2015 at 8:42
  • Similar question to: stackoverflow.com/questions/15111698/… and stackoverflow.com/questions/15111698/… Commented Oct 11, 2015 at 8:43
  • @dwnenr Since my post 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 :) Commented Nov 4, 2015 at 10:10

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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

    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.