Вы находитесь на странице: 1из 9

Working with Collections in C#

The .NET Framework has powerful support for Collections. Collections are
enumerable data structures that can be assessed using indexes or keys. This
article discusses Collections in .NET with code examples.
The System.Collections namespace
The System.Collections namespace provides a lot of classes, methods and
properties to interact with the varying data structures that are supported by it.
The interfaces that are defined in this namespace include:
· IEnumerable
· IEnumerator
· ICollection
· IList
· IDictionary
The following are the classes that are derived from the ICollection interface.
· System.Collections.Stack
· System.Collections.Queue
· System.Collections.BitArray
· System.Collections.Specialized.NameValueCollection
The IDictionary interface represents collections that have name value pairs. The
collections that inherit the IDictionary interface include:
· System.Collections.SortedList
· System.Collections.Hashtable
· System.Collections.Specialized.HybridDictionary
· System.Collections.Specialized.ListDictionary
The IList interface represents collections that only have value. The following are
the classes that extend this interface.
· System.Array
· System.Collections.ArrayList
· System.Collections.Specialized.StringCollection
The IEnumerable Interface
An enumerator is an object that provides a forward, read-only cursor for a set of
items. The IEnumerable interface has one method called the GetEnumerator()
method. This method returns an object that implements the IEnumerator
interface. The code snippet below illustrates how an enumerator can be used to
iterate though a list or collection of items.
Listing 1
String names[]=new String[2] {”Joydip”,”Jini”};
for(IEnumerator e =names.GetEnumerator();e.MoveNext();Response.Write(e.Cur
rent));
Note that the GetEnumerator() method returns an enumerator object each time it
is called. Further, the loop contains the Response.Write statement in its re-
initializer portion, which is perfectly valid. The condition being evaluated is
whether the MoveNext() method returns a value of true. The MoveNext() method
returns true as long as there are items in the collection. The Current property
returns the current object and is automatically typecast to string by making a call
to the ToString() method implicitly.
The foreach method can also be used in this case, as it calls the enumerator
implicitly. The above code can be re-written using a foreach loop as follows:
Listing 2
String names[]=new String[2] {”Joydip”,”Jini”};
foreach(string str in names)
Response.Write(str);
ArrayList
The ArrayList class is a dynamic array of heterogeneous objects. Note that in an
array we can store only objects of the same type. In an ArrayList, however, we
can have different type of objects; these in turn would be stored as object type
only. We can have an ArrayList object that stores integer, float, string, etc., but
all these objects would only be stored as object type. An ArrayList uses its
indexes to refer to a particular object stored in its collection. The Count property
gives the total number of items stored in the ArrayList object. The Capacity
property gets or sets the number of items that the ArrayList object can contain.
Objects are added using the Add() method of the ArrayList and removed using its
Remove() method. An example of usage of an ArrayList is given below.
Listing 3
using System;
using System.Collections;

class Test
{
static void Main()
{
int i = 100;
double d = 20.5;
ArrayList arrayList = new ArrayList();
arrayList.Add("Joydip");
arrayList.Add(i);
arrayList.Add(d);
for (int index = 0; index <arrayList.Count; index++)
Console.WriteLine(arrayList[index]);
}
}
It is to be noted here that the initial capacity of an ArrayList is 16, which is
increased once the 17th item is stored onto it. This repeated memory allocation
and copying of the items can be quite expensive in some situations. For
performance reasons we can set the initial capacity of the object of an ArrayList
by using the Capacity property or an overloaded constructor of the ArrayList
class. This is shown in the example below.
Listing 4
using System;
using System.Collections;

class Test
{
static void Main()
{
int i = 100;
double d = 20.5;
ArrayList arrayList = new ArrayList();
arrayList.Capacity = 2;
arrayList.Add("Joydip");
arrayList.Add(i);
arrayList.Add(d);
for (int index = 0; index <arrayList.Count; index++)
Console.WriteLine(arrayList[index]);
}
}
StringCollection
The StringCollection class implements the IList interface and is like an ArrayList of
strings. The following code example shows how we can work with a
StringCollection class.
Listing 5
using System;
using System.Collections;
using System.Collections.Specialized;

class Test
{
static void Main()
{
StringCollection stringList = newStringCollection();
stringList.Add("Manashi");
stringList.Add("Joydip");
stringList.Add("Jini");
stringList.Add("Piku");

foreach (string str in stringList)


{
Console.WriteLine(str);
}

}
}
StringDictionary
Similar to the StringCollection class we have the StringDictionary class, which is
just a Hashtable that has its keys as strings only. Remember that a Hashtable
can contain any object type in its key. The following code shows how we can
work with a StringDictionary class.
Listing 6
using System;
using System.Collections;
using System.Collections.Specialized;

class Test
{
static void Main()
{
StringDictionary stringList = newStringDictionary();
stringList.Add("A", "Manashi");
stringList.Add("B","Joydip");
stringList.Add("C","Jini");
stringList.Add("D","Piku");

foreach (string str in stringList.Values)


{
Console.WriteLine(str);
}

}
}
Stack
The Stack class is one that provides a Last-in-First-out (LIFO) collection of items
of the System.Object type. The last added item is always at the top of the Stack
and is also the first one to be removed. The following code sample shows how we
can use a Stack class for LIFO operation on its collection of items.
Listing 7
using System;
using System.Collections;

class Test
{
static void Main()
{
Stack stackObject = new Stack();
stackObject.Push("Joydip");
stackObject.Push("Steve");
stackObject.Push("Jini");
while (stackObject.Count > 0)
Console.WriteLine(stackObject.Pop());
Console.ReadLine();
}
}
The Push() method is responsible for storing items in the Stack and the method
Pop() removes them one at a time from the top of the Stack.
Queue
Unlike the Stack class, the Queue is a data structure that provides a First-in-First-
out collection of items of the System.Object type. The newly added items are
stored at the end or the rear of the Queue and items are deleted from the front of
the Queue. The following code shows how the Queue class can be used.
Listing 8
using System;
using System.Collections;

class Test
{
static void Main()
{
Queue queueObject = new Queue();
queueObject.Enqueue("Joydip");
queueObject.Enqueue("Steve");
queueObject.Enqueue("Jini");
while (queueObject.Count > 0)
Console.WriteLine(queueObject.Dequeue());
Console.ReadLine();
}
}
The Enqueue() method is responsible for storing items at the rear of the Queue
and the method Dequeue() removes them one at a time from the front of the
Queue.
BitArray
The BitArray class can be used to store bits in an array. They can be set to true
or false, depending on the parameter supplied at the time of creating the BitArray
object. The following is an example of its usage.
BitArray bitArray = new BitArray(5,false);
Or
BitArray bitArray = new BitArray(5,true);
Similar to the other collections discussed above, the BitArray class also contains
the Count property to get the number of items stored in this collection of bit
values. The following methods of the BitArray class allow logical bit operation.
· And
· Or
· Not
· Xor
Hashtable
The Hashtable provides a faster way of storage and retrieval of items of the
object type. The Hashtable class provides support for key based searching.
These keys are unique hash codes that are unique to a specific type. The
GetHashCode() method of the Hashtable class returns the hash code for an object
instance. The following code snippet shows how we can use a Hashtable class.
Listing 9
using System;
using System.Collections;

class Test
{
static void Main()
{
Hashtable hashTable = new Hashtable();
hashTable.Add(1, "Joydip");
hashTable.Add(2, "Manashi");
hashTable.Add(3, "Jini");
hashTable.Add(4, "Piku");
Console.WriteLine("The keysare:--");
foreach (int k in hashTable.Keys)
{
Console.WriteLine(k);
}

Console.WriteLine("Please enter the keyto search");


int p = int.Parse(Console.ReadLine());
Console.WriteLine(hashTable[3].ToString());
}
}
To remove an item from the Hashtable class, the Remove() method is used. The
statement hashTable.Remove(3) would remove the item “Jini” from the Hashtable
object created in the above code. The code shown above can also be written as
shown below to display the contents of the Hashtable object using
IDictionaryEnumerator.
Listing 10
using System;
using System.Collections;

class Test
{
static void Main()
{
Hashtable hashTable = new Hashtable();
hashTable.Add(1, "Joydip");
hashTable.Add(2, "Manashi");
hashTable.Add(3, "Jini");
hashTable.Add(4, "Piku");
Console.WriteLine("The keysare:--");
IDictionaryEnumerator en =hashTable.GetEnumerator();
string str = String.Empty;

while (en.MoveNext())
{
str = en.Value.ToString();
Console.WriteLine(str);
}
}
}
SortedList
The SortedList class allows items of the System.Object type to be placed in the
collection using key value pairs and, at the same time, supports sorting. The
following code shows how we can use a SortedList.
Listing 11
using System;
using System.Collections;
using System.Collections.Specialized;

class Test
{
static void Main()
{
SortedList sortedList = new SortedList();
sortedList.Add(1, "Manashi");
sortedList.Add(3, "Joydip");
sortedList.Add(2, "Jini");
sortedList.Add(4, "Piku");

Console.WriteLine("Displaying thenames");

foreach (string str in sortedList.Values)


{
Console.WriteLine(str);
}

}
}
The output of the above code is:
Manashi
Jini
Joydip
Piku
The same code can be written using IDictionaryEnumerator to display all the
items of the SortedList object, as shown below.
Listing 12
using System;
using System.Collections;
using System.Collections.Specialized;

class Test
{
static void Main()
{
SortedList sortedList = new SortedList();
sortedList.Add(1, "Manashi");
sortedList.Add(3, "Joydip");
sortedList.Add(2, "Jini");
sortedList.Add(4, "Piku");
Console.WriteLine("Displaying thenames");
IDictionaryEnumerator en = sortedList.GetEnumerator();
string str = String.Empty;
while (en.MoveNext())
{
str = en.Value.ToString();
Console.WriteLine(str);
}
}
}
Type Safe Collections
Type safe collections are those that comprise of a known type. It would support
indexing as an array and has a lot of benefits. A strong typed collection is
implemented using any of the following classes.
· CollectionBase
· ReadOnlyCollectionBase
· DictionaryBase
The following are the advantages of using strong typed collections.
· Supports indexing
· Supports enumeration
· Supports dynamic resizing
· Supports serialization
Implementing a Custom Collection Class
The following section shows how we can implement a custom collection class.
The following code shows how we can use the "design a custom collection class"
by sub-classing the CollectionBase class.
Listing 13
using System;
using System.Collections;
public class Product: CollectionBase
{
public Product this[int index]
{
get
{
return ((Product)(List[index]));
}
set
{
List[index] = value;
}
}

public bool Contains(Product product)


{
return List.Contains(product);
}

public int Add(Product Product)


{
return List.Add(Product);
}

public void Insert(int index, Product product)


{
List.Insert(index, product);
}

public void Remove(Product product)


{
List.Remove(Product);
}
}
The following code shows how we can use the "design a custom collection class"
by sub-classing the DictionaryBase class.
Listing 14
using System;
using System.Collections;

public class Product: DictionaryBase


{
public Product this[int index]
{
get
{
return ((Product)(Dictionary[index]));
}
set
{
Dictionary[index] = value;
}
}
public bool Contains(Product product)
{
return Dictionary.Contains(product);
}

public int Add(Product Product)


{
return Dictionary.Add(Product);
}

public void Insert(int index, Product product)


{
Dictionary.Insert(index, product);
}

public void Remove(Product product)


{
Dictionary.Remove(Product);
}
}

Вам также может понравиться