Home > DeveloperSection > Beginner > Collection in C#

Collection in C#


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

Collection in C#


Introduction:


Collection is an enhancement of array. Collection classes are specialized class for storing and retrieving a data. In most cases you can implement same interface in collection. Collection class are using for various purpose, such as allocating a memory dynamically to element and accessing a list of item on the basis of  an index etc. Collection are create a collection of object of the object class which is the base class for all in C#.

For example, you want to creating and managing a groups of related objects. In C#, there are two ways to create groups objects: first one is by creating an arrays of objects and second one is by creating a collections of objects.

Collections are providing a more flexibility to work with groups of objects. Unlike in array, you don’t use a dynamically i.e. fixed number of strongly- typed objects.

In some collections, we can assign a key to any object that you can put into the collection so that you can quickly retrieval the object by using the key.

Before declaration a collection class you must create an instance then add elements to that collection.

If you want to define collection class that can work with only one data type then you can use one of the class in the System.Collections.Generic namespace. You can’t added other data type that provide enforces type safety. If you are working with generic collection then you don’t need to determine its data type or conversion.

 

Using a simple Collection:


Using a simple collection, we can define collection as a strongly typed i.e. single data type are as follow:

The following example are using collection  for creating a list of strings and then iterates all elements in the list by using a foreach statement in C#.

// Create a list of strings.
// var listex = new List<string> {“Apple", "Mango", "Banana", "Papaya”};
var listex = new List<string>();
listex.Add("Apple");
listex.Add("Mango");
listex.Add("Banana");
listex.Add("Papaya");
 
// Iterate through the list.
foreach (var pr in listex)
{
    Console.Write(pr + " ");
}

// Output: Apple Mango Banana Papaya


Collection Classes:


Most commonly use collections are provided by the .NET Framework. Each type of collection is designed for a specific purpose. There are some of the common collection classes are define below:

1.      System.Collections.Generic classes:

A generic collection is useful when every item in the collection has the same data type. A generic collection enforces strong typing by allowing only the desired data type to be added.Some of the most using classes in the System.Collections.Generic namespace:

 

  • ·         Dictionary<TKey, TValue>:  Represents s collection of key/value pairs that are                                                                                                          organized based on the key.

  • ·         List<T>:    Represents a list of objects that can be accessed by index. Provide                                          methods to search, sort modify lists.

  • ·         Queue<T>:  FIFO Collection of objects.

  • ·         SortedList<TKey,TValue>: Represents a collection of key/value pairs that sorted                                               by key based on the associated IComparer<T> implementation.


 2.   System.Collections.Concurrent classes:  provide efficient thread-safe operations for accessing collection items from multiple threads.

3.      System.Collections classes: The classes in the System.Collections namespace do not store elements as specifically typed objects, but as objects of type Object.

Whenever possible, you should use the generic collections in the System.Collections.Generic namespace or the System.Collections.Concurrent namespace instead of the legacy types in the System.Collections namespace. Some of the most using classes in the System.Collections namespace:

I.                    ArrayList: Represents an array of objects whose size is dynamically increased as required.

II.                  Hash Table: Represents a collection of key/value pairs that are organized based on the hash code of the key.

III.                Queue: Represents a First in First Out (FIFO) collections of objects.

IV.                Stack: Represents a Last in First out (LIFO) collections of objects.

4.     Visual Basic Collection class:

 

Implementing a collection of Key/Value Pairs:


           The Dictionary<TKey, TValue> generic collection accessing the elements using the key of each element. Each addition to the dictionary consists of a value and its associated key. Retrieving a value by using its key is fast because the Dictionary class is implemented as a hash table.

For example, we are adding some string values in dictionary with associated a key pair and display it. we also check key pair is present in dictionary or not. After that remove one pair and then we will check key pair or found in dictionary or not.   

using System;
using System.Collections.Generic;
namespace DictionaryEx
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(@"## Lets us try to use of Dictionary Class
            ## i.e. defined in System.Collections.Generic namespace.");
            Console.WriteLine();
            Dictionary<string,int> dictionaryEx = new Dictionary<string,int>();
            dictionaryEx.Add("Anupam",1);
            dictionaryEx.Add("Ashish", 2);
            dictionaryEx.Add("Brijesh",3);
            dictionaryEx.Add("chanchal",4);
            foreach (KeyValuePair<string, int> p in dictionaryEx)
            {
                Console.WriteLine(p.Key.ToString() + ": " + p.Value.ToString());
            }
            Console.WriteLine();
            Console.WriteLine(@"## by passing keys check value are in the dictionary or not:");
            Console.WriteLine();
            // by passing keys check value are in the dictionary or not
            if (dictionaryEx.ContainsValue(2))
            {
                Console.WriteLine(true);
            }
            else
            {
                Console.WriteLine(false);
            }
             Console.WriteLine();
            //removing elements
            dictionaryEx.Remove("chanchal");
            Console.WriteLine(@"## After remove 'chanchal' printing  the element:");
            Console.WriteLine();
            foreach (KeyValuePair<string, int> p in dictionaryEx)
            {
                Console.WriteLine(p.Key.ToString() + ": " + p.Value.ToString());
            }
            Console.WriteLine();
            Console.WriteLine(@"## After Remove 'chanchal' check in dictionary is found or not  :");
            Console.WriteLine();
            if (dictionaryEx.ContainsValue(4))
            {                Console.WriteLine(true);
            }
            else
            {
                Console.WriteLine(false);
            }
            Console.ReadKey();
        }
    }
}

 Output:


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

Follow MindStick