-1

I have an exrecise on which i have to write a method which get Queue and remove each part of it who`s in the queue more than once for example: for 11223344 It wil return a queue with 1234

How can i do it?

user3419789
  • 27
  • 1
  • 8

2 Answers2

1

You can use the Distinct() function of an IEnumerable:

Queue<int> a = new Queue<int>(); // This is the queue from which you want to remove duplicates.
Queue<int> result = new Queue<int>(a.Distinct());

A Queue is essentially a collection, thus an IEnumerable and hence the LINQ extension methods for IEnumerable types can be called.


Here's a demo : .NET Fiddle Link

Fᴀʀʜᴀɴ Aɴᴀᴍ
  • 6,131
  • 5
  • 31
  • 52
0

This is basically a duplication:

Depending on you input:

  • if you have a sorted integer queue, you dequeue each element and queue it only once. When you're back to the first integer (lower than previous), you stop.
  • use a hashtable/dictionary as temporary storage to efficiently find duplicates.
  • a simple solution (not most efficient and needs quite a lot temporary memory and would be bad if you have several millions of elements in your queue) would be to use Linq like new Queue(queueWithDuplicates.Distinct());

More reads of how distinct works: How does LINQ .distinct method sort?

Community
  • 1
  • 1