C# Collections

    1 Votes

In C# a collection is known as the group of objects. In C#, .NET Framework provides specialized classes for the data storage and retrieval. Collection classes provide facility of stacks, queues, lists and hash tables. Collection classes implement the same interfaces and these interfaces can be inherited to create new collection classes.

In C# collection classes supports five general types of collections: non-generic, specialized, bit based, generic and concurrent. The non generic collection implements the dynamic array, stack and queue. Collection classes are defined as part of the System.Collections and they are not type safe. Most collection classes derive from the interfaces ICollection, IComparer, IEnumerable, IList, IDictionary and IEnumerator.

Generic Collections

Generic Collections are recommended, because it provides the benefit of type safety without having to derive from a base collection type and implement the type-specific members. Generic collections are better than the corresponding non-generic collection. Generic collections are classes, structures, interfaces and methods that contain placeholders (type parameters).

A generic collections class use a type parameter as a placeholder for the type of objects it stores and use. The examples of generic collection are IDictionary, IComparer, IEnumerator, IEnumerable, IList, Array list.

IEnumerable and IEnumerator

IEnumerable is the non-generic interface that a class must implement to support enumerators. It supports a simple iteration over a non-generic collection. It is inherited by ICollection. To better understand IEnumerable let us take an example.

using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
    static void Main()
    {
	IEnumerable result = from value in Enumerable.Range(0, 2)
				  select value;
	// Loop.
	foreach (int value in result)
	{
	    Console.WriteLine(value);
	}
	// We can use extension methods on IEnumerable
	double average = result.Average();
	// Extension methods can convert IEnumerable
	List list = result.ToList();
	int[] array = result.ToArray();
    }
}

Output:
0
1

IEnumerator is the interface that defines the functionality of an enumerator. Using its methods, we can cycle through the contents of a collection. It defines the methods MoveNext(), Reset etc.

using System; 
using System.Collections; 
class Student
{
	private int Rollno;
	private string Name;
	private int Age; 
	public Student(int rollno, string name, int age)
	{
	 this.Rollno = rollno;
	 this.Name = name;
	 this.Age = age;
	} 
	public int ROLLNO
	{
	 get
	 {
	  return this.Rollno;
	 }
	} 
	public override string ToString()
	{
	 return "Rollno:" + this.Rollno.ToString() + "\nName:" + Name + "\nAge:" + Age.ToString();
	}
} 
class Students:IEnumerable,IEnumerator
{
	ArrayList StuList=new ArrayList();
	private int Position=-1;
	public void AddStudent(Student oStu)
	{
	  StuList.Add(oStu);
	} 
	/*Implementing IEnumerable*/ 
	public IEnumerator GetEnumerator()
	{
	  return (IEnumerator)this;
	} 
	/*Implementing IEnumerator*/
	public bool MoveNext()
	{
	  if(Position<StuList.Count-1)
	  {
	    ++Position;
	    return true;
	  }
	  return false;
	} 
	public void Reset()
	{
	  Position=-1;
	} 
	public object Current
	{
	  get
	  {
	    return StuList[Position];
	  }
} 
public static void Main()
{
	Students StuList=new Students();
	Student s1=new Student(1,"Rahul",21);
	Student s2=new Student(2,"Samdish",24);
	StuList.AddStudent(s1);
	StuList.AddStudent(s2); 
	Console.WriteLine("Enumerating students using foreach");
	foreach(Student stu in StuList)
	{
	 Console.WriteLine(stu);
	} 
	Console.WriteLine("\nEnumerating student creating object of IEnumerator");
	IEnumerator StuEnumerator=StuList.GetEnumerator();
	StuEnumerator.Reset(); 
	while(StuEnumerator.MoveNext())
	{
	 Console.WriteLine((Student)StuEnumerator.Current);
	}
	}
}

Output:
Enumerating students using foreach
Rollno:1
Name:Rahul
Age:21
Rollno:2
Name:Samdish
Age:24

Enumerating student creating object of IEnumerator
Rollno:1
Name:Rahul
Age:21
Rollno:2
Name:Samdish
Age:24

IList and IComparer

IList defines the collection that can be accessed via an indexer. IList inherits ICollection and IEnumerable. Some methods of IList are:

  • intAdd(object o) – To add new objects in IList.
  • void clear( ) – To remove all items from IList.
  • void Insert(int index, object o) – To insert one new object into IList at a specific location.

The properties of IList are:

  • Count – It will return number of object in IList.
  • IsReadOnly – It tells whether the IList is read only or not.
  • Item – It will return the specific item from specific index.

To better understand IList let us have an example.

using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
    class Program
    {
       public static void Main(string[] args)
        {
            IList List = new List();
            List.Add("Samdish");
            List.Add("John");
            List.Add("Shahid");
 
            foreach (string name in List)
            {
                Console.WriteLine(name);
            }
            Console.ReadLine();
        }
    }
}

Output:
Samdish
John
Shahid

IComparer defines the Compare method that performs the comparison on objects stored in a collection. The method of IComparer is intCompare(object x, object y). Greater than zero if x is greater, less than zero if y is greater and zero if values are same. Let us take an example to better understand the concept.

using System;
using System.Collections.Generic;
class Student : IComparable
{
    public int Marks { get; set; }
    public string Name { get; set; }
    public int CompareTo(Student other)
    {
	// Alphabetic sort if marks is equal [A to Z]
	if (this.Marks == other.Marks)
	{
	    return this.Name.CompareTo(other.Name);
	}
	// Default to marks sort. [High to low]
	return other.Marks.CompareTo(this.Marks);
    }
    public override string ToString()
    {
	// String representation.
	return this.Marks.ToString() + "," + this.Name;
    }
}
class Program
{
    static void Main()
    {
	List list = new List();
	list.Add(new Student() { Name = "Shyam", Marks = 40 });
	list.Add(new Student() { Name = "John", Marks = 65 });
	list.Add(new Student() { Name = "Ajay", Marks = 100 });
	list.Add(new Student() { Name = "Raj", Marks = 50 });
	// Uses IComparable.CompareTo()
	list.Sort();
	// Uses Student.ToString
	foreach (var element in list)
	{
	    Console.WriteLine(element);
	}
    }
} 

Output:
100,Ajay
65,John
50,Raj
40,Shyam

Stack

Stack is first in last out list. Stack is implemented as a circular buffer. The capacity of a Stack can be initialized by the total number of elements the stack can hold. The elements are added to a stack, the capacity is automatically increased as required through reallocation. The collection class that supports stack is Stack.

It implements ICollection, IEnumerable and ICloneable interfaces. Stack accepts null as a valid value and allows duplicate elements. The stack represents the variable size as last-in-first-out (LIFO) in the collection of instances of the same arbitrary type. The methods are:

  • Push ( ) – Add the elements on the top of stack.
  • Pop ( ) – It will return the elements from the top of the stack and remove it from the collection.
  • Peek ( ) – It is same as Pop but it does not remove elements from the collection.
  • Count ( ) – It will count the elements from the stack.
  • Clear ( ) – It will clear the stack.

Let us have an example to understand it:

using System;
using System.Collections;
public class SamplesStack  {
    public static void Main()  {
       // Creates and initializes a new Stack.
       Stack myStack = new Stack();
       myStack.Push("Hello");
       myStack.Push("Welcome");
       myStack.Push("To");
       myStack.Push("C#");
       Console.WriteLine( "myStack" );
       Console.WriteLine( "Count: {0}", myStack.Count );
       Console.Write( "Values:" );
       PrintValues( myStack );
    }
    public static void PrintValues( IEnumerable myCollection )  {
       foreach ( Object obj in myCollection )
          Console.Write( " {0} ", obj );
       Console.WriteLine();
    }
 }

Output:
myStack
Count: 4
Values: C# To Welcome Hello

Array List

It supports dynamic arrays which can grow or shrink as needed. It is a variable length array of object references that can dynamically changes. It is created with an initial size and can be increased when the size is exceeded. It implement ICollection, IList, IEnumerable and ICloneable.

Constructors:

public ArrayList()
public ArrayList(ICollection c)
public ArrayList(int capacity)

Capacity grows automatically as elements are added to the list. It can store any type of objects but for searching and sorting those objects to be comparable. Let us have an example:

using System;
using System.Collections;
class Program
{
    static void Main()
    {
	// Create an ArrayList and add two ints.
	ArrayList list = new ArrayList();
	list.Add(1);
	list.Add(2);
	// Use ArrayList with method.
	Example(list);
    }
    static void Example(ArrayList list)
    {
	foreach (int i in list)
	{
	    Console.WriteLine(i);
	}
    }
}

Output:
1
2

Dictionary

It represents a dictionary in C# that is used to represent a collection of keys and values pair of data. The Dictionary class is a generic class and it can store any data types. This class is defined in the System.Collections.Generic namespace. The properties are:

  • Count – It gets the number of keys or values pairs in a dictionary.
  • Item - It gets and sets the value with the specified key.
  • Keys - It defines the collection containing the keys in the dictionary.
  • Values – It defines the collection containing the values in the dictionary.

Let us understand through example:

using System;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
            Dictionary<string, double> dict = new Dictionary<string, double>();
            dict.Add("komal", 10000);
            dict.Add("Deepti", 20000);
            dict.Add("madhav",5000);
            ICollection c = dict.Keys;

            foreach (string str in c)
                Console.WriteLine("name is " + str +  "salary is " + dict[str]);
            Console.ReadLine();
    }
} 

Output:
name is komalsalary is 10000
name is Deeptisalary is 20000
name is madhavsalary is 5000