1

I have two Integer stacks StackA and StackB.

StackA has the following values but StackB has no content.

StackA
-----
[40]
[11]
[56]
[10]
[11]
[56]

Now i need to copy distinct values from StackA to StackB.I tried this

    public static void CopyDistinctValues(Stack<int> source, Stack<int> destination)
    {
        int[] numArray = source.ToArray();
        for (int i = 0; i < numArray.Length; i++)
        {
            if (!destination.Contains(numArray[i]))
            {
                destination.Push(numArray[i]);
            }
        }
    }

and its working but i am not sure if its the best solution.

Is there a better way to do this or any built in method to achieve this?

It will be better if it can be done without using Array.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Qwerty
  • 578
  • 1
  • 5
  • 31

3 Answers3

5

The shortest way would be:

stackB = new Stack<int>(stackA.Distinct().Reverse());

Reverse is required because constructor takes IEnumerable and Stack's implementation of IEnumerable makes it to start from the last item.

preciousbetine
  • 2,959
  • 3
  • 13
  • 29
Piotr Wojsa
  • 938
  • 8
  • 22
  • but your code works inline not in the CopyDistiinctValues method call – Qwerty Feb 05 '19 at 08:09
  • 1
    I want to point out that Distinct is a set operation and as such the results are unordered (see the remark under https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.distinct). So it's not guaranteed that the new stack has them in the right order. Depending on how Distinct is implemented it may be ordered though, but this implementation detail may change in later .NET versions. – ckuri Feb 05 '19 at 08:13
0

What if you use Linq in this case like

Stack<int> stacka = new Stack<int>(new[] { 40, 11, 56, 10, 11, 56 });
Stack<int> stackb = new Stack<int>(stacka.ToArray().Distinct());
Rahul
  • 76,197
  • 13
  • 71
  • 125
0
            Stack<int> StackA= new Stack<int>();
            StackA.Push(2);
            StackA.Push(3);
            StackA.Push(4);
            StackA.Push(5);
            StackA.Push(2);
            Stack<int> StackB = new Stack<int>();
            StackB = new Stack<int>(StackA.Distinct());
xoxo
  • 1,248
  • 14
  • 19