Home / C Sharp / C# Collections and Generics / Archive by category 'C# Collections Examples'

C# Collections Examples

stack<T> collection in c#

An example of stack<T> use in c#:

Stack<int> stack = new Stack <int>();
stack.Push(1);
stack.Push(2);
int x = stack.Pop() / / x is 2
int y = stack.Pop() / / y is 1

Use an iterator to return a sequence of Fibonacci numbers in C#

using System;
using System;
 
class FibTest
{
  static void Main ()
  {
    foreach (int fib in Fibs (6))
      Console.Write (fib + "");
  }
 
  static IEnumerable <int> Fibs (int fibCount)
  {
    for (int i = 0, prevFib = 1, curFib = 1; i <fibCount; i++)
    {
      yield return prevFib;
      int = newFib prevFib curFib +;
      prevFib = curFib;
      curFib = newFib;
    }
  }
}

Output: 1 1 2 3 5 8


Using GetEnumerator to access characters in C# string

Below is an example of using GetEnumerator method of a collection to access characters in a string and display them.

var enumerator = "This is my string".GetEnumerator();
 
while (enumerator.MoveNext())
{
  var element = enumerator.Current ;
  Console.WriteLine (element);
}

Iterate through arraylist and use indexer

using System;
using System.Collections;
 
 
class CollectionsDemo {
    public static void Main(String[] args) {
 
 
        ArrayList PokerPlayers = new ArrayList(3);
        PokerPlayers.Add("J");
        PokerPlayers.Add("M");
        PokerPlayers.Add("A");
        PokerPlayers.Add("J");
 
 
        foreach (String Player in PokerPlayers) {
            Console.WriteLine(Player);
        }
 
 
        PokerPlayers[0] = "A";
        System.Console.WriteLine(PokerPlayers[0]);
    }
}

Example of array length property on 3d array

 
// Use the Length array property on a 3-D array. 
 
using System; 
 
public class LengthDemo3D {  
  public static void Main() {  
    int[,,] nums = new int[10, 5, 6];  
 
    Console.WriteLine("Length of nums is " + nums.Length);  
 
  }  
}

Example use of array length property

 
// Use the Length array property.  
 
using System; 
 
public class LengthDemo {  
  public static void Main() {  
    int[] nums = new int[10];  
 
    Console.WriteLine("Length of nums is " + nums.Length);  
 
    for(int i=0; i < nums.Length; i++)  
      nums[i] = i * i;  
 
    Console.Write("Here is nums: "); 
    for(int i=0; i < nums.Length; i++)  
      Console.Write(nums[i] + " ");  
 
    Console.WriteLine(); 
  }  
}

Example use of array.copy() method to copy part of an array

 
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
 
 
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
 
 
//
//  CopyPart.cs -- Uses the Array.Copy() method to copy part of an array
//                 ints into a secton of an array of doubles.
//
//                 Compile this program with the following command line:
//                     C:>csc CopyPart.cs
//
namespace nsArray
{
    using System;
 
    public class CopyPart
    {
        static public void Main ()
        {
            DateTime now = DateTime.Now;
            Random rand = new Random ((int) now.Millisecond);
            int [] iArr = new int [12]
                    {
                        rand.Next() % 101, rand.Next() % 101,
                        rand.Next() % 101, rand.Next() % 101,
                        rand.Next() % 101, rand.Next() % 101,
                        rand.Next() % 101, rand.Next() % 101,
                        rand.Next() % 101, rand.Next() % 101,
                        rand.Next() % 101, rand.Next() % 101
                    };
 
            double [] dArr = new double [14];
            Array.Copy (iArr, 2, dArr, 4, 8);
            Console.Write ("The dArr contains:\r\n    ");
            for (int x = 0; x < dArr.Length; ++x)
            {
                Console.Write ("{0,4:F1}  ", dArr[x]);
                if (x == 6)
                    Console.Write("\r\n    ");
            }
            Console.Write ("\r\n\r\nThe iArr contains:\r\n    ");
            foreach (int x in iArr)
            {
                Console.Write (x + "  ");
            }
            Console.WriteLine ();
        }
    }
}

Use array.copy() method to copy an array with type cast

 
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
 
 
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//
//  Int2Dbl.cs -- Uses the Array.Copy() method to copy an array of ints
//                into an array of doubles.
//
//                Compile this program with the following command line:
//                    C:>csc Int2Dbl.cs
//
namespace nsArray
{
    using System;
 
    public class Int2Dbl
    {
        static public void Main ()
        {
            DateTime now = DateTime.Now;
            Random rand = new Random ((int) now.Millisecond);
            int [] iArr = new int [10]
                    {
                        rand.Next() % 101, rand.Next() % 101,
                        rand.Next() % 101, rand.Next() % 101,
                        rand.Next() % 101, rand.Next() % 101,
                        rand.Next() % 101, rand.Next() % 101,
                        rand.Next() % 101, rand.Next() % 101
                    };
 
            double [] dArr = new double [8];
            Array.Copy (iArr, dArr, dArr.Length);
            Console.Write ("The dArr contains:\r\n    ");
            foreach (double d in dArr)
            {
                Console.Write ("{0,4:F1}  ", d);
            }
            Console.Write ("\r\n\r\nThe iArr contains:\r\n    ");
            foreach (int x in iArr)
            {
                Console.Write (x + "  ");
            }
            Console.WriteLine ();
        }
    }
}

Sorteddictionary to store instance of system.icomparable

using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
 
 
 
 
public class Customer : System.IComparable {
    private int _id;
    private string _name;
    private string _rating;
    private static SortOrder _order;
 
 
    public enum SortOrder {
        Ascending = 0,
        Descending = 1
    }
 
 
    public Customer(int id, string name)
        : this(id, name, "Other") {
    }
 
 
    public Customer(int id, string name, string rating) {
        this._id = id;
        this._name = name;
        this._rating = rating;
    }
 
 
    public int Id {
        get { return this._id; }
        set { this._id = value; }
    }
 
 
    public string Name {
        get { return this._name; }
        set { this._name = value; }
    }
 
 
    public string Rating {
        get { return this._rating; }
        set { this._rating = value; }
    }
 
 
    public static SortOrder Order {
        get { return _order; }
        set { _order = value; }
    }
 
 
    public override bool Equals(Object obj) {
        bool retVal = false;
        if (obj != null) {
            Customer custObj = (Customer)obj;
            if ((custObj.Id == this.Id) &&
                (custObj.Name.Equals(this.Name) &&
                (custObj.Rating.Equals(this.Rating))))
                retVal = true;
        }
        return retVal;
    }
 
 
    public override string ToString() {
        return this._id + ": " + this._name;
    }
 
 
    public int CompareTo(Object obj) {
        switch (_order) {
            case SortOrder.Ascending:
                return this.Name.CompareTo(((Customer)obj).Name);
            case SortOrder.Descending:
                return (((Customer)obj).Name).CompareTo(this.Name);
            default:
                return this.Name.CompareTo(((Customer)obj).Name);
        }
    }
}
 
 
class Program {
    public static void Main(){
        Dictionary<int, Customer> custDict = new Dictionary<int, Customer>();
        custDict[99] = new Customer(99, "H", "P");
        custDict[77] = new Customer(77, "B", "G");
        custDict[55] = new Customer(55, "B", "S");
        custDict[88] = new Customer(88, "B", "P");
 
 
        Dictionary<int, Customer>.ValueCollection unsortedValues;
        unsortedValues = custDict.Values;
        foreach (Customer cust in unsortedValues)
            Console.Out.WriteLine("Customer Name: {0}", cust.Name);
 
 
        SortedDictionary<int, Customer> sortedDict;
        sortedDict = new SortedDictionary<int, Customer>(custDict);
 
 
        SortedDictionary<int, Customer>.ValueCollection sortedValues;
        sortedValues = sortedDict.Values;
        foreach (Customer cust in sortedValues) {
            Console.Out.WriteLine("Customer->{0}", cust.Name);
        }
 
 
        sortedDict.Remove(88);
 
 
        sortedValues = sortedDict.Values;
        foreach (Customer cust in sortedValues) {
            Console.Out.WriteLine("Customer->{0}", cust.Name);
        }
    }
}

Example use of a two-dimensional array

 
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
 
 
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// Grades.cs -- Uses a two-dimensional array to store grades for students
//
//              Compile this program with the following command line:
//                  C:>csc Grades.cs
namespace nsGrades
{
    using System;
 
    public class Grades
    {
        static public void Main ()
        {
             DateTime now = DateTime.Now;
             Random rand = new Random ((int) now.Millisecond);
 
 
             int [,] Grades = new int [5,10];
             for (int x = 0; x < Grades.GetLength (0); ++x)
             {
                 for (int y = 0; y < Grades.GetLength(1); ++y)
                 {
                     Grades [x, y] = 70 + rand.Next () % 31;
                 }
             }
             int [] Average = new int [10];
             Console.WriteLine ("Grade summary:\r\n");
             Console.WriteLine ("Student   1   2   3   4   5   6   7   8   9  10");
             Console.WriteLine ("        ----------------------------------------");
 
 
             for (int x = 0; x < Grades.GetLength (0); ++x)
             {
                 Console.Write ("Test " + (x + 1) + " ");
                 for (int y = 0; y < Grades.GetLength(1); ++y)
                 {
                     Average[y] += Grades[x,y];
                     Console.Write ("{0,4:D}", Grades[x,y]);
                 }
                 Console.WriteLine ();
             }
             Console.Write ("\r\n Avg.  ");
             foreach (int Avg in Average)
             {
                 Console.Write ("{0,4:D}", Avg / Grades.GetLength(0));
             }
             Console.WriteLine ();
        }
    }
}

Recursive implementation of binary search in csharp

using System;
 
 
public class BinarySearch {
  public static int Search (int[] data, int key, int left, int right) {
    if (left <= right) { 
      int middle = (left + right)/2;       
      if (key == data[middle])
        return middle;
      else if (key < data[middle])
        return Search(data,key,left,middle-1);
      else 
        return Search(data,key,middle+1,right);
    }
    return -1;   
  }
  public static void Main(String[] args) {
    int key;       // the search key
    int index;     // the index returned
    int[] data = new int[10];
 
    for(int i = 0; i < data.Length; i++)
      data[i] = i;
 
    key = 9;
    index = Search(data, key, 0, data.Length-1);
    if (index == -1)
      Console.WriteLine("Key {0} not found", key);
    else
      Console.WriteLine ("Key {0} found at index {1}", key, index);
  }
}

Example use of a jagged array to store data

 
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
 
 
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// Sales.cs -- Uses a jagged array to store sales figures, then writes report
//             for one month. Demonstrates that you do not have to worry about
//             looking for empty elements.
//
//             Compile this program with the following command line:
//                 C:>csc Sales.cs
//
namespace nsSales
{
    using System;
 
    public class Sales
    {
        static public void Main ()
        {
             DateTime now = DateTime.Now;
             Random rand = new Random ((int) now.Millisecond);
             int [] MonthLen = new int []
                           {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
             double [][] Sales2000 = new double [12][];
             for (int x = 0; x < MonthLen.Length; ++x)
             {
                 Sales2000[x] = new double [MonthLen[x]];
                 for (int y = 0; y < Sales2000[x].Length; ++y)
                 {
                     Sales2000[x][y] = rand.NextDouble() * 100;// % 11 + 20;
                 }
             }
             Console.Write ("February Sales Report (in thousands):");
             for (int x = 0; x < Sales2000[1].Length; ++x)
             {
                  if ((x % 4) == 0)
                      Console.WriteLine ();
                  Console.Write ("    Feb. {0,-2:D}: {1,-4:F1}", x + 1, Sales2000[1][x]);
             }
        }
    }
}

Example use of readonlycollection to wrap a collection

using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
 
 
 
 
public class Customer : System.IComparable {
    private int _id;
    private string _name;
    private string _rating;
    private static SortOrder _order;
 
 
    public enum SortOrder {
        Ascending = 0,
        Descending = 1
    }
 
 
    public Customer(int id, string name)
        : this(id, name, "Other") {
    }
 
 
    public Customer(int id, string name, string rating) {
        this._id = id;
        this._name = name;
        this._rating = rating;
    }
 
 
    public int Id {
        get { return this._id; }
        set { this._id = value; }
    }
 
 
    public string Name {
        get { return this._name; }
        set { this._name = value; }
    }
 
 
    public string Rating {
        get { return this._rating; }
        set { this._rating = value; }
    }
 
 
    public static SortOrder Order {
        get { return _order; }
        set { _order = value; }
    }
 
 
    public override bool Equals(Object obj) {
        bool retVal = false;
        if (obj != null) {
            Customer custObj = (Customer)obj;
            if ((custObj.Id == this.Id) &&
                (custObj.Name.Equals(this.Name) &&
                (custObj.Rating.Equals(this.Rating))))
                retVal = true;
        }
        return retVal;
    }
 
 
    public override string ToString() {
        return this._id + ": " + this._name;
    }
 
 
    public int CompareTo(Object obj) {
        switch (_order) {
            case SortOrder.Ascending:
                return this.Name.CompareTo(((Customer)obj).Name);
            case SortOrder.Descending:
                return (((Customer)obj).Name).CompareTo(this.Name);
            default:
                return this.Name.CompareTo(((Customer)obj).Name);
        }
    }
}
 
 
class Program {
    public static void Main(){
        List<Customer> collCustList = new List<Customer>();
        collCustList.Add(new Customer(99, "H", "P"));
        collCustList.Add(new Customer(77, "B", "G"));
        collCustList.Add(new Customer(55, "B", "G"));
        collCustList.Add(new Customer(88, "B", "P"));
        collCustList.Add(new Customer(11, "L", "O"));
 
 
        ReadOnlyCollection<Customer> roCustColl = new ReadOnlyCollection<Customer>(collCustList);
 
 
        Customer tmpCust = roCustColl[1];
        tmpCust.Name = "NAME CHANGED";
 
 
        foreach (Customer cust in roCustColl)
            Console.Out.WriteLine(cust);
    }
}

Example use of object to create a generic array

 
/*
C#: The Complete Reference 
by Herbert Schildt 
 
 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
 
 
 
 
// Use object to create a generic array. 
 
using System; 
 
public class GenericDemo {   
  public static void Main() {   
    object[] ga = new object[10]; 
 
    // store ints 
    for(int i=0; i < 3; i++) 
      ga[i] = i; 
 
    // store doubles 
    for(int i=3; i < 6; i++) 
      ga[i] = (double) i / 2;  
 
 
    // store two strings, a bool, and a char 
    ga[6] = "Generic Array"; 
    ga[7] = true; 
    ga[8] = 'X'; 
    ga[9] = "end"; 
 
    for(int i = 0; i < ga.Length; i++) 
      Console.WriteLine("ga[" + i + "]: " + ga[i] + " "); 
 
  }  
}

Example use of icomparer

 
/*
C#: The Complete Reference 
by Herbert Schildt 
 
 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
 
 
// Use IComparer. 
 
using System; 
using System.Collections; 
 
// Create an IComparer for Inventory objects. 
class CompInv : IComparer { 
  // Implement the IComparable interface. 
  public int Compare(object obj1, object obj2) { 
    Inventory a, b; 
    a = (Inventory) obj1; 
    b = (Inventory) obj2; 
    return a.name.CompareTo(b.name); 
  } 
} 
 
class Inventory { 
  public string name; 
  double cost; 
  int onhand; 
 
  public Inventory(string n, double c, int h) { 
    name = n; 
    cost = c; 
    onhand = h; 
  } 
 
  public override string ToString() { 
    return 
      String.Format("{0,-10}Cost: {1,6:C}  On hand: {2}", 
                    name, cost, onhand); 
  } 
} 
 
public class MailList { 
  public static void Main() { 
    CompInv comp = new CompInv(); 
    ArrayList inv = new ArrayList(); 
 
    // Add elements to the list 
    inv.Add(new Inventory("Pliers", 5.95, 3)); 
    inv.Add(new Inventory("Wrenches", 8.29, 2));    
    inv.Add(new Inventory("Hammers", 3.50, 4)); 
    inv.Add(new Inventory("Drills", 19.88, 8)); 
 
    Console.WriteLine("Inventory list before sorting:"); 
    foreach(Inventory i in inv) { 
      Console.WriteLine("   " + i); 
    } 
    Console.WriteLine(); 
 
    // Sort the list using an IComparer. 
    inv.Sort(comp); 
 
    Console.WriteLine("Inventory list after sorting:"); 
    foreach(Inventory i in inv) { 
      Console.WriteLine("   " + i); 
    } 
  } 
}

Example use of bitarray collection as flag

using System;
using System.Collections;
 
 
public class Starter {
    public static void Main() {
        Hashtable employees = new Hashtable();
        employees.Add("A100", new Employee("Ben", true, false, true));
        employees.Add("V100", new Employee("Valerie", false, false, true));
        Participation((Employee)employees["A100"]);
        Participation((Employee)employees["V100"]);
    }
 
 
    public static void Participation(Employee person) {
        Console.WriteLine(person.Name + ":");
        if (person.InProfitSharing) {
            Console.WriteLine(" Participating in Profit Sharing");
        }
        if (person.InHealthPlan) {
            Console.WriteLine(" Participating in Health Plan");
        }
        if (person.InCreditUnion) {
            Console.WriteLine(" Participating in Credit Union");
        }
    }
}
 
 
public class Employee {
 
 
    public Employee(string emplName) {
        propName = emplName;
        eflags.SetAll(true);
    }
 
 
    public Employee(string emplName,
                    bool profitSharing,
                    bool healthPlan,
                    bool creditUnion) {
        propName = emplName;
        InProfitSharing = profitSharing;
        InHealthPlan = healthPlan;
 
 
        InCreditUnion = creditUnion;
    }
 
 
    private BitArray eflags = new BitArray(3);
 
 
    public bool InProfitSharing {
        set {
            eflags.Set(0, value);
        }
        get {
            return eflags.Get(0);
        }
    }
 
 
    public bool InHealthPlan {
        set {
            eflags.Set(1, value);
        }
        get {
            return eflags.Get(1);
        }
    }
 
 
    public bool InCreditUnion {
        set {
            eflags.Set(2, value);
        }
        get {
            return eflags.Get(2);
        }
    }
 
 
    private string propName;
    public string Name {
        get {
            return propName;
        }
    }
}

Example of three-dimensional rectangular array

 
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
 
 
Publisher: Sybex;
ISBN: 0782129110
*/
 
 
/*
  Example10_8.cs illustrates the use of
  a three-dimensional rectangular array
*/
 
 
using System;
 
 
public class Example10_8
{
 
 
  public static void Main()
  {
 
 
    // create the galaxy array
    int[,,] galaxy = new int [10, 5, 3];
 
 
    // set two galaxy array elements to the star's brightness
    galaxy[1, 3, 2] = 3;
    galaxy[4, 1, 2] = 9;
 
 
    // display the Rank and Length properties of the galaxy array
    Console.WriteLine("galaxy.Rank (number of dimensions) = " + galaxy.Rank);
    Console.WriteLine("galaxy.Length (number of elements) = " + galaxy.Length);
 
 
    // display the galaxy array elements, but only display elements that
    // have actually been set to a value (or "contain stars")
    for (int x = 0; x < galaxy.GetLength(0); x++)
    {
      for (int y = 0; y < galaxy.GetLength(1); y++)
      {
        for (int z = 0; z < galaxy.GetLength(2); z++)
        {
          if (galaxy[x, y, z] != 0)
          {
            Console.WriteLine("galaxy[" + x + ", " + y + ", " + z +"] = " +
              galaxy[x, y, z]);
          }
        }
      }
    }
 
 
  }
 
 
}

Example of jagged array in csharp

 
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
 
 
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example10_9.cs illustrates the use of a jagged array
*/
 
 
using System;
 
 
public class Example10_9
{
 
 
  public static void Main()
  {
 
 
    // declare a jagged array of four rows,
    // with each row consisting of a string array
    string[][] names = new string[4][];
 
 
    // the first row is an array of three strings
    names[0] = new string[3];
    names[0][0] = "Jason";
    names[0][1] = "Marcus";
    names[0][2] = "Price";
 
 
    // the second row is an array of two strings
    names[1] = new string[2];
    names[1][0] = "Steve";
    names[1][1] = "Smith";
 
 
    // the third row is an array of four strings
    names[2] = new string[] {"Cynthia", "Ann", "Jane", "Williams"};
    names[3] = new string[] {"Gail", "Jones"};
 
 
    // display the Rank and Length properties for the names array
    Console.WriteLine("names.Rank = " + names.Rank);
    Console.WriteLine("names.Length = " + names.Length);
 
 
    // display the Rank and Length properties for the arrays
    // in each row of the names array
    for (int row = 0; row < names.Length; row++)
    {
      Console.WriteLine("names[" + row + "].Rank = " + names[row].Rank);
      Console.WriteLine("names[" + row + "].Length = " + names[row].Length);
    }
 
 
    // display the array elements for each row in the names array
    for (int row = 0; row < names.Length; row++)
    {
      for (int element = 0; element < names[row].Length; element++)
      {
        Console.WriteLine("names[" + row + "][" + element + "] = " +
          names[row][element]);
      }
    }
 
 
  }
 
 
}

Inbuilt system.array reverse method

using System;
 
 
public class SystemArrayTypeReverse
{
    public static void Main()
    {
        int[] arr = {5, 6, 7};
        Array.Reverse(arr);
        foreach (int value in arr)
        {
            Console.WriteLine("Value: {0}", value);
        }
    }
}

Inbuilt system.array sorting

using System;
 
 
public class SortingandSearchingArray
{
    public static void Main()
    {
        int[]    arr = {5, 1, 10, 33, 100, 4};
 
        Array.Sort(arr);
        foreach (int v in arr)
        Console.WriteLine("Element: {0}", v);
    }
}