Sponsored Ad

Thursday, October 22, 2009

Collections In C#

To construct plus manipulate a collection of objects, .Net framework has provided us with lots of classes. ArrayList, BitArray, HashTable, SortedList, Queue plus Stack are some of them. They are all included in Process.Collections namespace.

In general, arrays are not dynamic in nature and not allow the user to easily remove an item. An ArrayList is like an extensible set of objects. Your add, insert, delete forms RemoveAt make it relatively easy to insert and remove items from ArrayList. But it can not refer to an entry in an ArrayList by a keyword. HastTable solves this problem, but does not allow tickets to be addressed by indices. Furthermore, it allows us to retrieve the entries in a particular order. SortedList represents a set of keys and associated values. The values are ordered by number and are accessible by key and by index.

The following code example shows how to write a collection class that can be used with foreach. The class is a flag string, similar to the C run-time function

/ tokens.cs
using System;
// The System.Collections namespace is made available:
using System.Collections;

// Declare the Tokens class:
public class Tokens : IEnumerable
{
   private string[] elements;

   Tokens(string source, char[] delimiters)
   {
      // Parse the string into tokens:
      elements = source.Split(delimiters);
   }

   // IEnumerable Interface Implementation:
   //   Declaration of the GetEnumerator() method
   //   required by IEnumerable
   public IEnumerator GetEnumerator()
   {
      return new TokenEnumerator(this);
   }

   // Inner class implements IEnumerator interface:
   private class TokenEnumerator : IEnumerator
   {
      private int position = -1;
      private Tokens t;

      public TokenEnumerator(Tokens t)
      {
         this.t = t;
      }

      // Declare the MoveNext method required by IEnumerator:
      public bool MoveNext()
      {
         if (position < t.elements.Length - 1)
         {
            position++;
            return true;
         }
         else
         {
            return false;
         }
      }

      // Declare the Reset method required by IEnumerator:
      public void Reset()
      {
         position = -1;
      }

      // Declare the Current property required by IEnumerator:
      public object Current
      {
         get
         {
            return t.elements[position];
         }
      }
   }

   // Test Tokens, TokenEnumerator

   static void Main()
   {
      // Testing Tokens by breaking the string into tokens:
      Tokens f = new Tokens("This is a well-done program.",
         new char[] {' ','-'});
      foreach (string item in f)
      {
         Console.WriteLine(item);
      }
   }
}

0 comments:

Post a Comment

Sponsored Ad

Website Update

Followers