Collection in C#

Collections are required to create and manage groups of related objects. 

Object can be grouped by array or collections.  Arrays useful for working with fixed number for strongly typed items. Collection provide more flexible way, it can grow or shrink dynamically as per need. Also some collection can work as key-value pair.

Collection is class so it need to initiate. Collection can be generic to force type safety. Collection can be created in following ways:-
var Colors = new List<string>();
        Colors.Add("Green");       
(OR)

var Colors = new List<string> { "Green", "Red", "pink", "white" };  

There are multiple collection type provided by .net where each have different purpose. Following are some of collection type. 

  •      • Arraylist:- Represents an array of objects whose size is dynamically increased as required.
  •      • Hashtable:- Represents a collection of key/value pairs that are organized based on the hash code of the key.
  •      • Queue:- Represents a first in, first out (FIFO) collection of objects.
  •      • Stack:- Represents a last in, first out (LIFO) collection of objects.

This collection can be generic as follows’:- 

  •      • Dictionary<TKey,TValue>
  •      • Queue<T>
  •      • Stack<T>

We have some other genric collections as,

  •      • List<T> Represents a list of objects that can be accessed by index. Provides methods to search, sort, and modify lists.
  •      • SortedList<TKey,TValue> Represents a collection of key/value pairs that are sorted by key based on the associated IComparer<T> implementation.

Linq can be used to access collections, also it implements IComparable<T> interface which implements CompareTo method so sorting can be done easily. E.g. Colors.Sort();



Defining a Custom Collection
Collection can be defined by implementing the IEnumerable<T> or IEnumerable interface. Typical example is when we covert generic list into Selectlist it will give you IEnumerable collection.

The difference between IEnumerable and Genric collection is IEnumerable not allow to add and or remove item. But can be joined with another IEnumerable list.

IEnumerable Vs IQueryable
IQueryable is an interface that implements IEnumerable, So it has all thing IEnumerable have plus additionaly have some methods. The main difference is that with IEnumerable you get all the records at once while with IQueryable you only get the records that you want. 

Let consider belwo example,
    1. IEnumerable<Colors> clients = db.Colors.Take(2).ToList();
    2. IQueryable<Colors> sameClients = db. Colors.Take(2).ToList();
        
In case of IEnumerable, Here all the colors are loaded in memory first and then it will pick first 2
While in case of IQueryable, only 2 colors will get loaded.


Comments