Add extension method to List - CSharp Collection

CSharp examples for Collection:List

Description

Add extension method to List

Demo Code

using System;/*from w w w  . j a v a  2 s . c o  m*/
using System.Collections.Generic;
using System.Text;
public static class ListExtensions
{
   public static Stack<T> ToStack<T>(this List<T> list)
   {
      Stack<T> stack = new Stack<T>();
      foreach (var item in list)
      {
         stack.Push(item);
      }
      return stack;
   }
}
class Program
{
   static void Main(string[] args)
   {
      List<string> colors = new List<string>()
      {
         "A",
         "B",
         "C",
         "D"
      };
      var stack = colors.ToStack();
      Console.Write("Colors - List: ");
      foreach(var color in colors)
      {
         Console.Write($"{color} ");
      }
      Console.WriteLine();
      Console.Write("Colors - Stack: ");
      while(stack.Count > 0)
      {
         Console.Write($"{stack.Pop()} ");
      }
   }
}

Result


Related Tutorials