The Collection namespace of System contains many classes and interfaces, which provides to define various collections of objects. These interfaces and classes are useful for every programmer to develop big or large applications.
The .NET Framework provides a rich suite of collection classes, including Array, ArrayList, NameValueCollection, StringCollection, Queue, Stack, and BitArray.
Arrays in C# are implemented as instance of System.Array class, and are just one type known as collection classes.
We’ll be covering the following topics in this tutorial:
System.Array
The Array class has a number of useful methods which extend the capabilities of arrays and make them smarter than arrays seen in other languages.
Two useful static methods of Array are Sort( ) and Reverse( ).These are fully supported for the built-in C# types such as string. Example demonstrates the use of these two methods to manipulate String objects
Using Array.Sort and Array.Reverse
using System;
using System.collections;
public class Tester
{
public static void printMyArray(object[] Arr)
{
foreach (object obj in Arr)
console.writeline(“value: {O}”, obj);
Console.writeline(“\n”);
}
static void Main()
{
String[] Arr1 ={“world”, “is”, “Beautiful”};
console.writeline(“Original array is :”);
printMyArray(Arr01);
Array.Reverse(Arr1);
Console.writeline(“After reverse array is :”);
printMyArray(Arr1);
String [] Arr2 ={“see”,”it” ,”from” ,”your” ,”heart” ,”eyes”};
console.writeline(“Original array is :”);
printMyArray(Arr2);
Array.sort(Arr2);
console.writeline(“After sort array is :”);
printMyArray(Arr2);
}
}
OUTPUT:
Original Array is:
Value: World
Value: is
Value: Beautiful
After Reveres Array is:
Value: Beautiful
Value: is
Value: World
Original Array is:
Value: See
Value: it
Value: from
Value: your
Value: heart
Value: eyes
After Sort array is:
Value: eyes
Value: from
Value: heart
Value: it
Value: See
Value: your
The .NET Framework provides standard interfaces for enumerating, comparing, and creating collections. The key collection interfaces are listed.
The System.Array class inherits from IList, ICollection, and IEnumerable interfaces, but doesn’t support some of more advanced features of IList and represents, a list of items with a fixed size.
ArrayLists
The classic problem with the Array type is its fixed size. If you do not know in advance how many objects an array will hold, you run the risk of declaring either too small an array (and running out of room) or too large an array (and wasting memory).
Your program might be asking the user for input, or gathering input from a web site. it finds objects (strings, books, values, etc.) you will add them to the array, but you have no idea how many objects you’ll collect in any given session. The classic fixed-size array is not a good choice, as you can’t predict how large an array you’ll need.
The ArrayList class is an array whose size is dynamically increased as required. ArrayLists provide a number of useful methods and properties for their manipulation.
When you create an ArrayList, you do not define how many objects it will contain. You add to the ArrayList using the Add( ) method, and the list takes care of its own internal bookkeeping, as illustrated in simple.
Working with an ArrayList
using system;
using system.collections;
public class Tester
{
static void Main( )
{
ArrayList number = new ArrayList( );
//adding the elements to ArrayList
foreach(int num in new
int[10]{10,9,10,23,45,56,9,12,78,64})
{
number.Add(num);
}
//adding another item out of loop
Number.add(34);
//remove first element whose value is 9
Number.remove(9);
//remove the element of 7th position
Number.removeat(6);
//display the content of arraylist
Console.writeline(“:element of arraylist”);
For(int i=0;i!=number.count;i++)
{
Int num =(int)number[i];
Console.write(num + “,”);
}
//sort the existing elements of ArrayList
number.sort();
console.writeLine(“\nsorted List”);
.for(int i=O;i!=number.count;i++)
{
int num =(int)number[i];
console.write(num+”,”);
}
}
}
OUTPUT:
Elements of ArrayList
10,10,23,45,56,9,78,64,34
Sorted List
9,10,10,23,34,45,56,64,78
Queue
A queue represents a first-in, first-out (FIFO) collection. The classic analogy is to a line at a ticket window. The first person in line ought to be the first person to come off the line to buy a ticket.
A queue is a good collection to use when you are managing a limited resource. For example, you might want to send messages to a resource which can only handle one message at a time.
You would then create a message queue so that you can say to your clients: “Your message is important to us. Messages are handled in the order in which they are received.”
You can add elements to your queue with the Enqueue command and you can take them off the queue with Dequeue or by using an enumerator.
Working with a queue
using System;
using system.collections;
public class Tester
{
static void Main( )
{
Queue number = new Queue( );
//adding the elements to Queue
foreach(int num in new
int[lO]{lO,9,lO,23,45,56,9,12,78,64})
{
number.Enqueue(num);
}
//adding another item out of loop
number.Enqueue(34)
// remove first element
number.Dequeue();
II view the first element in the
II Queue but do not remove.
Console.writeLine(“\n(peek) \t{O}”, number.peek( ) );
//display the content of Queue
console.writeLine(“\ncontents of Queue”);
printvalues(number);
}
public static voidprintvalues( IEnumerable mycollection )
{
IEnumerator myEnumerator = mycollection.GetEnumerator( );
while ( myEnumerator.MoveNext( ) )
console.write( “{O} “,myEnumerator.current );
Console.writeLine( );
}
}
OUTPUT:
(peek) 9
Contents of Queue:
9 10 23 45 56 9 12 78 64 34
Stacks
A stack is a last-in, first-out (LIFO) collection, like a stack of dishes at a buffet table, or a stack of coins on your desk. You add a dish on top, and that is the first dish you take off the stack.
The principal methods for adding to and removing from a stack are Push( )and Pop( ); Stack also offers a Peek( ) method, very much like Queue.
The ArrayList, Queue, and Stack types contain overloaded CopyTo( ) and ToArray( ) methods for copying their elements to an array. In the case of a Stack, the CopyTo( ) method will copy its elements to an existing one-dimensional array, overwriting the contents of the array beginning at the index you specify. The ToArray( ) method returns a new array with the contents of the stack’s elements.
Working with a Stack
using System;
using System.collections;
public class Tester
{
static void Main( )
{
stack intStack = new Stack( );
II populate the array
for (int i = 0;i<8;i++)
{
intStack.push(i*5);
}
// Display the stack.
console.write( “intStack values:\t” );
printvalues( intStack );
// Remove an element from the stack
Console.writeLine( “\n(pop)\t{O}”, intstack.pop( ) );
// Display the stack
Console.write( “intStack values:\t” );
printvalues( intStack );
// Remove another element from the Stack
Console.writeLine( “\n(pop)\t{O}”, intStack.pop( ) );
// display the Stack
console.write( “intstack values:\t” );
printvalues( intStack );
// view the first element in the
// Stack but do not remove.
Conso1e.writeLine ( “\n(peek) \t{O}”, intStack .Peek( ) );
// Display the Stack
Console.write( “intStack values:\t” );
printvalues( intStack );
}
public static void printvalues( IEnumerable mycollection )
{
IEnumerator myEnumerator = myCollection.GetEnumerator( );
while ( myEnumerator.MoveNext( ) )
console.write( ”{0} “,myEnumerator.current );
console.writeLine( );
}
}
OUTPUT:
intStack values: 35 30 25 20 15 10 5 0
(Pop) 35
intStack values: 30 25 20 15 10 5 0
(Pop) 30
intStack values: 25 20 15 10 5 0
(Peek) 25
intStack values: 25 20 15 10 5 0
Hashtables
A hashtable is a dictionary optimized for fast retrieval. In a Hashtable, each value is stored in a “bucket.” The bucket is numbered, much like an offset into an array.
Because the key may not be an integer, it must be possible to translate the key (e.g., “Massachusetts”) into a bucket number. Each key must provide a hash code, a GetHashCode ( ) method will accomplish this magic.
You will remember that everything in C# derives from object. The object class provides a virtual method GetHashCode( ), which the derived types are free to inherit as is or to override. A trivial implementation of a GetHashCode( ) function for a string might simply add up the Unicode values of each character in the string and then use the modulus operator to return a value between 0 and the number of buckets in the Hashtable. It is not necessary to write such a method for the string type, however, as the CLR provides one for you.
When you insert the values (the state capitals) into the Hashtable, the Hashtable calls GetHashCode( ) on each key we provide. This method returns an int, which identifies the bucket into which the state capital is placed.
It is possible, of course, for more than one key to return the same bucket number. This is called a collision. There are a number of ways to handle a collision. The most common solution, and the one adopted by the CLR, is simply to have each bucket maintain an ordered list of values. When you retrieve a value from the Hashtable, you provide- a key. Once again the Hashtable calls GetHashCode( ) on the key and uses the returned int to find the appropriate bucket. If there is only one value, it is returned. If there is more than one value, a binary search of the bucket’s contents is performed. Because there are few values, this search is typically very fast. see an example
Working with a HashTable
using System;
using System.collections;
// a simple class to store in the array
public class Tester
{
static void Main( )
{
// Create and initialize a new Hashtable.
Hashtable hashTable = new Hashtable( );
hashTable.Add(“000440312”, “Jesse Liberty”);
hashTable.Add(“OOOl23933″, ‘~Stacey Liberty”);
hashTable.Add(“000145938”, “John Galt”);
hashTable.Add(“000773394”, “Ayn Rand”);
// access a particular item
console.writeLine(“{O} “,hashTable[“000145938”]);
}
}
OUTPUT:
John Galt
SortedList
Some times you might want to provide a mapping where the type you map from isn’t int but rather some other type (string, double). The SortedList class provides this functionality by internally maintaining two objects arrays- one for keys, one for values.
The key array is always sorted.
In contrast to other collection classes, you don’t have control of where the element live in a SortedList. A SortedList can’t contain duplicate keys. however, if you use the squre bracket notation to add a key/value pair, then its ok.
When use a foreach statement to iterate a SortedList, you get back a DictionaryEntry which provides access to the elements in both arrays thru the Key property and Value property.
using System;
using System.collections;
public class Tester
{
static void Main( )
{
SortedList map = new SortedList();
string[] keys = {“these”,”are”,”the”,”keys”};
//adding the elements to sortedList
for(int i=O;i!=keys.Length;i++)
{
string k = keys[i];
int v = i;
map[k] = v;
}
console.writeLine(“\ncontent of SortedList”);
foreach(dictionaryEntry element in map)
{
string k = (string) element.Key;
int v = (int)element.value;
console.writeLine(“key: {O},\tvalue: {l}”,k,v);
}
}
}
OUTPUT:
Content of SortedList
key: are, Value: 1
key: keys, Value: 3
key: the, Value: 2
key: these, Value: 0