Home > DeveloperSection > Articles > Collections in C#

Collections in C#


C# C# 
Ratings:
0 Comment(s)
 4129  View(s)
Rate this:

Collections in C#

This article discusses one of the most important parts of .Net Framework: Collections. In C#, a collection is a group of objects. Simply, Collection represents a set of objects that you can access by stepping through each element in turn. The .NET Framework provides specialized classes for managing collection and these classes have rich capability for enhancing your programming experience through better performance and easy maintenance.

The principal benefits of collections are that they standardize the way groups of objects are handled by your programs. All collections are designed around a set of cleanly defined interfaces.  Several built-in implementations of these interfaces, such as Array List, Hashtables, Stack and Queue etc, are provided, which you can use as-is. You can also implement your own collection, but you will seldom need to.      

The .Net framework contains a large number of interfaces and classes that define and implement various types of collection.  Object class is the base class of every type in .NET. All the collections implement IEnumerable interface that is extended by ICollection interface. IDictionary and IList are also interfaces for collection which are derived from ICollection as shown in below diagram.

Collections in C#

System.ICollection.IEnumerable:

It exposes the enumerator, which provides a collection, according to user defined classes.

Methods:

GetEnumerator (): It returns the enumerator object that can be used to iterate through the collection. It allows using the foreach statement. Enumerators only allow reading the data in the collection.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Collections;

 

namespace CollectionTestDemo

{

    class Program

    {

        static void Main(string[] args)

        {

            Array arry = new string[] { "John", "Miles", "Cooper", "Peter", "Hexi", "Mike" }; // user defines collection

            IEnumerator ienum = arry.GetEnumerator(); // convert in enumerator object

 

            string enumMsg = ""; // declare variable to hold items

            while(ienum.MoveNext())

            {

                string value = (string)ienum.Current; // get current enumerated object

                enumMsg += value + "\n";

            }

            Console.Write(enumMsg); // print message

            Console.ReadKey(); // hold console screen

        }

    }

}

 

 

Now execute above lines of code, following output will be visible.

Collections in C#

System.Collections.ICollection:

ICollection interface specifies a method for getting the size of collection, creating enumerators on a collection and managing synchronized access to all non-generic collections. It is a base interface for classes in the System.Collections namespace.

Briefly, The basic Differences between Generic Collection and Non-Generic Collection:

Non-Generic collections - These are the collections that can hold elements of different data types. It holds all elements as object type. So it includes overhead of type conversions.

Generic collections - These are the collections that can hold data of same type and we can decide what type of data that collections can hold.

Some advantages of generic collections - Type Safe, Secure, reduced overhead of type conversions.

Important Properties:

Count: It returns the number of items of contain by the ICollection.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Collections;

 

namespace CollectionTestDemo

{

    class Program

    {

        static void Main(string[] args)

        {

            ArrayList arryList = new ArrayList(); // declaring arraylist collection

            arryList.Add("Pike"); // adding string object

            arryList.Add("Whesley");

            arryList.Add("Carl");

            arryList.Add("Hodge");

 

            Console.Write("Collection items count: {0}",arryList.Count); // it will return count 4

            Console.ReadKey();

        }

    }

}

 

 

 

Code Clarification: In the above lines of code, declaring dynamic array and added four string object such as Pike, Whesley, Carl, Hodge etc, Count is property of ICollection interface which returns number of items in collection.

Collections in C#

IsSynchronized: It returns true if access to the ICollection is synchronized.

SyncRoot: It returns an object that can be used to synchronize access to the ICollection.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Collections;

 

namespace CollectionTestDemo

{

    class Program

    {

        static void Main(string[] args)

        {

            ArrayList arryList = new ArrayList(); // declaring arraylist collection

            arryList.Add("Pike"); // adding string object

            arryList.Add("Whesley");

            arryList.Add("Carl");

            arryList.Add("Hodge");

 

 

          lock (arryList.SyncRoot) // lock object to synchronize

            {

                string list = string.Empty; // declare variable to hold sync object

                foreach (var lst in arryList) // get syn object one by one

                {

                    if (list.Length > 0)  // logic to add ',' sign to after every object

                        list += ",";

                    list += lst.ToString();

                }

                Console.Write(list);

                Console.ReadKey();

            }

        }

    }

}

 

 

 

Code Clarification: In above code, declare lock statement to hold that arryList object which is going to synchronize.

Collections in C#

Important Methods:

CopyTo(): This method helps to copies the elements of the ICollection object to any array, starting at a particular Array index. If .NET is unable to cast source type to destination, then it throws ArrayTypeMismatchException exception.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Collections;

 

namespace CollectionTestDemo

{

    class Program

    {

        static void Main(string[] args)

        {

           

            ArrayList srcList = new ArrayList(); // declaring source array list collection

            srcList.Add("Pike"); // adding string object

            srcList.Add("Whesley");

            srcList.Add("Carl");

            srcList.Add("Hodge");

 

            string[] destList = new string[srcList.Count]; // declaring destination array list

            srcList.CopyTo(destList, 0); // copy source array list items to destination array from starting index 0

            // destList = {"Pike","Whesley","Carl","Hodge"}

 

            Console.WriteLine("Destination list items:");

            foreach (var lst in destList)

            {

                Console.WriteLine("{0}", lst.ToString());

            }

            Console.ReadKey();

        }

    }

}

 

 

 

Collections in C#

System.Collections.IList:

IList interface represents the collection of objects that can be individually accessed by index.  The implementation of IList has been divided into three categories: read-only, fixed-size, and variable-size. A read only IList cannot be modified. A fixed size IList does not allow the addition or removal of elements, but it allows the modification of the existing elements. A variables size IList allows the addition, removal, and modification of elements.

Important Properties:

IsFixedSize: It returns true if IList has fixed size.

 

ArrayList srcList = new ArrayList();

Console.Write(srcList.IsFixedSize); // returns- false because ArrayList is not fixed size

 

 

IsReadOnly: It returns true if IList is read only.

 

ArrayList arryList = new ArrayList(); // declaring source array list collection

            arryList.Add("Pike"); // adding string object

            arryList.Add("Whesley");

            arryList.Add("Carl");

            arryList.Add("Hodge");

 

            bool isRead = arryList.IsReadOnly; // returns false, because default array

                                               // list is defined readonly

            // Creating readonly arraylist

            ArrayList readOnlyList = ArrayList.ReadOnly(arryList); //assigning readonly arraylist

            bool isReadOnly = readOnlyList.IsReadOnly; // returns true

 

 

Important Methods:

Add ():

Add (object value):  It adds the item into the IList.

ArrayList arryList = new ArrayList(); // declaring source array list collection

            arryList.Add("Pike"); // adding first string object

            arryList.Add("Whesley"); // adding second string object

            arryList.Add("Carl"); // adding third string object

            arryList.Add("Hodge"); // adding four string object and so on you can add many more

 

 

Insert ():

Insert (int index, object value): 

It inserts an item to the IList at specific index. If index equals the number of items in the IList, then value is appended to the end, but if index greater than the number of items in the IList or less than zero, then it throws ArgumentOutOfRangeException exception. If you try to insert item in the read-only or fixed size IList then it throws NotSupportedException exception.

// declaring arraylist with default adding three items

            ArrayList arryList = new ArrayList();

            arryList.Add(new Testing(1, "Items1")); // adding first object of type Testing

            arryList.Add(new Testing(2, "Items2")); // adding second object of type Testing

            arryList.Add(new Testing(3, "Items3")); // adding third object of type Testing

 

            // Creating a new object of type Testing

            Testing tst = new Testing(4, "items4");

 

            arryList.Insert(3, tst); // insert items4 object

                                     // at index 2

 

 

 

Remove ():

Remove (object value):

It removes the first occurrence of a specific object from the IList. If you try to remove value from read only or fixed size IList, then it throws NotSupportedException.

ArrayList arryList = new ArrayList();

            arryList.Add(new Testing(1, "Items1")); // adding first object of type Testing

            arryList.Add(new Testing(2, "Items2")); // adding second object of type Testing

            arryList.Add(new Testing(3, "Items3")); // adding third object of type Testing

 

            // Creating a new object of type Testing

            Testing tst = new Testing(4, "items4");

            arryList.Remove(tst); // Remove tst object from collection

 

 

Contains ():

Contain (object value): It returns true if IList contain a specific value. This method uses the Equals and CompareTo methods to determine whether an item exists in Collection.

System.Collections.IDictionary:

It represents a collection of key/value pairs. IDictionary interface is implemented by classes that support collections of associated keys and values. Each element in a key/value pair is stored in a DictionaryEntry object. It allows the contained keys and values to be enumerated, but it does not imply any particular sort order.

Important Properties:

IsFixedSize:

It returns true if IDictionary object has a fixed size.

IsReadOnly:

It returns true if IDictionary object is read only.

Keys: It returns ICollection object containing keys of the IDictionary object.

Hashtable hashList = new Hashtable(); // declaring hastable collection

            hashList.Add(1, "Australia"); // adding string object "" with key value "1"

            hashList.Add(2, "India"); // adding string object "India" with key value "2"

            hashList.Add(3, "USA"); // adding string object "USA" with key value "3"

 

            ICollection keys = hashList.Keys; // get all keys from hastable collection

            string[] strKeys = new string[keys.Count]; // declare string array object to hold keys value

 

            int index = 0; // string array index

            foreach(var key in keys)

            {

                strKeys[index++] = key.ToString();  // assigning key value

            }

          Console.WriteLine("Keys value string :{0}", string.Join(", ", strKeys)); // print 3, 2, 1

 

          Console.ReadKey();

 

 

Values: It returns ICollection object containing values of the IDictionary object.

Hashtable hashList = new Hashtable(); // declaring hastable collection

            hashList.Add(1, "Australia"); // adding string object "" with key value "1"

            hashList.Add(2, "India"); // adding string object "India" with key value "2"

            hashList.Add(3, "USA"); // adding string object "USA" with key value "3"

 

            ICollection values = hashList.Values; // get all keys from hastable collection

            string[] strValues = new string[values.Count]; // declare string array object to hold keys value

 

            int index = 0; // string array index

            foreach (var val in values)

            {

                strValues[index++] = val.ToString();  // assigning key value

            }

            Console.WriteLine("Idictionary values string :{0}", string.Join(", ", strValues)); // return USA, India, Australia

            Console.ReadKey();

 

 

Important Methods:

Add ():

Add (object key, object value); adds an element with the specified key and value into the IDictionary object.

Hashtable hashList = new Hashtable(); // declaring hastable collection

            hashList.Add(1, "Australia"); // adding string object "" with key value "1"

            hashList.Add(2, "India"); // adding string object "India" with key value "2"

            hashList.Add(3, "USA"); // adding string object "USA" with key value "3"

 

 

Clear (): It removes all elements from the IDictionary object.

Hashtable hashList = new Hashtable(); // declaring hastable collection

            hashList.Add(1, "Australia"); // adding string object "" with key value "1"

            hashList.Add(2, "India"); // adding string object "India" with key value "2"

            hashList.Add(3, "USA"); // adding string object "USA" with key value "3"

 

            hashList.Clear(); // removes all elements from hashList

 

 

Removes ():

Remove (object key); It removes the element with the specified key from the IDictionary object.

Hashtable hashList = new Hashtable(); // declaring hastable collection

            hashList.Add(1, "Australia"); // adding string object "" with key value "1"

            hashList.Add(2, "India"); // adding string object "India" with key value "2"

            hashList.Add(3, "USA"); // adding string object "USA" with key value "3"

 

            hashList.Remove(1); // remove key 1 element from hashList

 


Don't want to miss updates? Please click the below button!

Follow MindStick