.NET Development Foundation/Using collections


System types and collections: Using collections


Using Collections edit

Exam objective: Manage a group of associated data in a .NET Framework application by using collections.

(Refer System.Collections namespace - MSDN)

ArrayList class edit

see MSDN

The ArrayList class is used for arrays whose size will dynamically increase as required. An ArrayList is not necessarily sorted.

using System;
using System.Collections;
public class Demo {
    public static void Main() {
        ArrayList myArrayList = new ArrayList();
        myArrayList.Add("Testing");
        myArrayList.Add("1...2...3");
    }
}
Collection interfaces edit
ICollection interface and IList interface
ICollection interface - MSDN
The ICollection interface is the base interface for classes in the System.Collections namespace.
The ICollection interface extends IEnumerable; IDictionary and IList are more specialized interfaces that extend ICollection. An IDictionary implementation is a collection of key/value pairs, like the Hashtable class. An IList implementation is a collection of values and its members can be accessed by index, like the ArrayList class.
Some collections that limit access to their elements, such as the Queue class and the Stack class, directly implement the ICollection interface.
If neither the IDictionary interface nor the IList interface meet the requirements of the required collection, derive the new collection class from the ICollection interface instead for more flexibility.
The following tables list the members exposed by the ICollection type.
Public Properties
  Count - Gets the number of elements contained in the ICollection.  
  IsSynchronized - Gets a value indicating whether access to the ICollection is synchronized (thread safe).  
  SyncRoot - Gets an object that can be used to synchronize access to the ICollection.  

Public Methods
  CopyTo - Copies the elements of the ICollection to an Array, starting at a particular Array index.   
IList interface - MSDN
IComparer interface, IEqualityComparer interface, and IKeyComparer interface
IComparer interface - MSDN
IEqualityComparer interface - MSDN
IKeyComparer interface - IKeyComparer does not exist in .Net 2.0
IDictionary interface and IDictionaryEnumerator interface
IDictionary interface - MSDN
IDictionaryEnumerator interface - MSDN
IEnumerable interface and IEnumerator interface - MSDN and MSDN
C# code sample

IEnumerator sample

public class Person
{
   public Person(string fName, string lName)
   {
       this.firstName = fName;
       this.lastName = lName;
   }
   public string firstName;
   public string lastName;
}
public class PeopleEnum : IEnumerator
{
   public Person[] _people;
   //Enumerators are positioned before the first element
   //until the first MoveNext() call.
   int position = -1;
   public PeopleEnum(Person[] list)
   {
       _people = list;
   }
   public bool MoveNext()
   {
       position++;
       return (position < _people.Length);
   }
   public void Reset()
   {
       position = -1;
   }
   public object Current
   {
       get
       {
           try
           {
               return _people[position];
           }
           catch (IndexOutOfRangeException)
           {
               throw new InvalidOperationException();
           }
       }
   }
}
public class People : IEnumerable
{
   private Person[] _people;
   public People(Person[] pArray)
   {
       _people = new Person[pArray.Length];
       for (int i = 0; i < pArray.Length; i++)
       {
           _people[i] = pArray[i];
       }
   }
   public IEnumerator GetEnumerator()
   {
       return new PeopleEnum(_people);
   }
}

Write down a handler for Practicing the above code.

protected void lnkEnumerator_Click(object sender, EventArgs e)
   {
       Person[] peopleArray = new Person[] {
           new Person("Irfan", "Akhtar"),
           new Person("Hammad", "Anwar"),
           new Person("Majid", "Aalim")     };
       PeopleEnum Prson = new PeopleEnum(peopleArray);
  • One way of using IEnumerator.
 while (Prson.MoveNext () )
 {
       Person P = (Person)Prson.Current;
       Response.Write("First Name : " + P.firstName + ", Last Name : " + P.lastName);
 }


  • One way of using IEnumerable.
People peopleList = new People(peopleArray);
foreach (Person p in peopleList)
    Response.Write("First Name : " + p.firstName + ", Last Name : " + p.lastName);
IHashCodeProvider interface - MSDN - Interface is now obsolete (as of .NET 2.0)

Iterators edit

See MSDN

An iterator is effectively a lightweight version of the IEnumerable interface. It is primarily used with foreach statements.
You will normally implement the GetEnumerator method of the IEnumerable interface.
public class Colors : System.Collections.IEnumerable
{
    string[] colors = { "Red", "Green", "Blue" };
    public System.Collections.IEnumerator GetEnumerator()
    {
        for (int i = 0; i < colors.Length; i++)
        {
            yield return colors[i];
        }
    }
}
This enables the class to be accessed using a standard foreach statement. A class is not restricted to implementing only a single iterator. Multiple iterators can be supplied, for example to enable iteration in both ascending and descending order of a list. To call a named iterator, use the following syntax:
foreach (int i in myList.NamedIterator())
{
    System.Console.WriteLine(i);
}
The yield statement marks a point where execution of a iterator will resume on a subsequent iteration. This can be used to supply multiple yield statements:
public System.Collections.IEnumerator GetEnumerator()
{
    yield return "Statement returned on iteration 1";
    yield return "Statement returned on iteration 2";
}
To end the iteration programmatically, use the
yield break;
statement.

Hashtable class - MSDN

Used to represent a collection of key/value pairs.

CollectionBase class and ReadOnlyCollectionBase class

CollectionBase class - MSDN
ReadOnlyCollectionBase class -MSDN

DictionaryBase class and DictionaryEntry class

DictionaryBase class - MSDN
DictionaryEntry structure - MSDN

Comparer class - MSDN

Queue class - MSDN

SortedList class - MSDN

BitArray class - MSDN

Stack class - MSDN

<noinclide>