Linq and Stack… Take versus Pop

So this might be filed under “Who f—ing cares” but I thought it was somewhat interesting. If you’ve ever used a Stack, you should be familiar with Pop and Peek. If not, here’s a little diddy from a guy named diddy. Actually that’s a lie. I have no affiliation Sean “Puffy” “Puff Daddy” “P Diddy” “Whatever he’s called now” Combs. We do share the same first name though. (Annnnnd wait for incoming lawsuit over using his name on this site)

A stack is a first in last in first out structure that in the .Net world uses two methods to get values back from it: Pop and Peek. Pop will give you the item AND remove it from the stack. Peek will merely give you the item but leave it safely on the stack.

What’s the point of this post? I’ll tell you when I find out.

Now when using Linq with a stack, you might get in trouble if you assume the Take method uses pop to get the value:

  return stackToUse.Take(count).ToList();

You would think that this would use Pop since Pop really is the “natural” (For lack of a better word) function of a stack. Most languages can guarantee a Push and Pop for stacks, but not all languages have a Peek. So it would be normal to assume the default is Pop. Problem is: It’s not. The Take method actually uses the Peek method. So these two methods will give a completely different return:

    ///Uses Pop
    ///  Return list with have "count" number of items and stackToUse will have the original
    ///    count of items minus "count"
    public static List<Object> CreateListFromPopOnStack(Stack<Object> stackToUse, Int32 count)
    {
      return Enumerable.Range(0, count).Select(item => stackToUse.Pop()).ToList();
    }

    ///Uses Take/Peek
    ///  Return list will have "count" number of items and stackToUse will have still have
    ///     the same number of items it came in with.
    public static List<Object> CreateListFromTakeOnStack(Stack<Object> stackToUse, Int32 count)
    {
      return stackToUse.Take(count).ToList();
    }

In the end, this is a rare case you will actually need to know, but what the hell? Why not know it?