You are on page 1of 34

System.

Collections
Namespace
The .NET framework provides specialized classes for data storage
and retrieval.

. NET Framework 4.6 and 4.5

TheSystem.Collectionsnamespace contains interfaces and


classes that define various collections of objects, such as lists,
queues, bit arrays, hash tables and dictionaries .

For many applications, you want to create and manage groups of related
objects. There are two ways to group objects: by creating arrays of
objects, & by creating collections of objects.
Arrays are most useful for creating and working with a fixed no. of
strongly-typed objects.
Collections provide a more flexible way to work with groups of objects.

Unlike arrays, the group of objects you work with can grow and shrink
dynamically as the needs of the application change. For some collections,
you can assign a key to any object that you put into the collection so that
you can quickly retrieve the object by using the key.
A collection is a class, so you must declare an instance of the class before
you can add elements to that collection. If your collection contains
elements of only one data type, you can use one of the classes in the
System.Collections.Genericnamespace.

Collection classes are specialized classes for data storage and retrieval which is an
enhancement for the Arrays. These classes provide support for stacks, queues, lists,
& hash tables. Most collection classes implement the same interfaces. Collection
classes serve various purposes, such as allocating memory dynamically to elements
and accessing a list of items on the basis of an index etc like array. These classes
create collections of objects of the Object class, which is the base class for all data
types in C#.

Using a simple
Collection

There are two distinct collection types in C#.


1.

The standard collections, which are found


under the

2.

System.Collections

The generic collections, under


System.Collections.Generic

Generic collections are more flexible and are the preferred way to
work with data.

The generic collections or generics were introduced


in .NET framework 2.0. Generics enhance code
reuse, type safety, and performance.

Generic programmingis a style of computer


programming in which algorithms are written in
terms of to-be-specified-later types that are
then instantiated when needed for specific
types provided as parameters.
This approach, pioneered by Ada in 1983,
permits writing common functions or types that
differ only in the set of types on which they
operate when used, thus reducing duplication.

Various Collection Classes and


Their Usage
1.
2.
3.
4.
5.
6.

Array List
HashTable
SortedList
Stack
Queue
BitArray

1. Array List
It represents ordered collection of an object that can be indexedindividually.
It is basically an alternative to an array. However, unlike array you can add and
remove items from a list at a specified position using anindexand the array
resizes itself automatically.
It also allows dynamic memory allocation, adding, searching and sorting items
in the list.

1. AnArrayListis a collection from a


standardSystem.Collectionsnamespace.
2. It is a dynamic array. It provides random access to its elements.
3. AnArrayListautomatically expands as data is added.
4. Unlike arrays, anArrayListcan hold data of multiple data types.
5. Elements in theArrayListare accessed via an integer index.
Indexes are zero based.
6. Indexing of elements and insertion and deletion at the end of
theArrayListtakes constant time.
7. Inserting or deleting an element in the middle of the dynamic
array is more costly. It takes linear time. T
8. This collection dynamically resizes. It grows in capacity as
elements are added (if space is needed). It is most often used
in older C# programs.

TheArrayListclass is designed to hold heterogeneous collections of objects. However, it does


not always offer the best performance. Instead, we recommend the following:
1. For a heterogeneous collection of objects, use theList<Object>(in C#) type.
2. For a homogeneous collection of objects, use theList<T>class.
TheArrayListis not guaranteed to be sorted. You must sort theArrayListby calling itsSort
method prior to performing operations (such asBinarySearch) that require theArrayListto be
sorted. To maintain a collection that is automatically sorted as new elements are added, you
can use theSortedSet<T>class.
The capacity of anArrayListis the number of elements theArrayListcan hold. As elements
are added to anArrayList, the capacity is automatically increased as required through
reallocation. The capacity can be decreased by callingTrimToSizeor by setting theCapacity
property explicitly.
For very largeArrayListobjects, you can increase the maximum capacity to 2 billion elements
on a 64-bit system by setting theenabledattribute of the configuration element totruein
the run-time environment.

2. Hash Table
It uses akeyto access the elements in the collection.
A hash table is used when you need to access elements by
using key, and you can identify a useful key value.
Each item in the hash table has akey/valuepair. The key is
used to access the items in the collection.

Hashtable

in

C#

represents a collection
of key/value pairs which
maps keys to value. Any
non-null object can be
used as a key but a
value

can.

retrieve

We

items

can
from

hashTable to provide the


key

Both

keys

values are Objects.

and

3. Sorted List
It uses akeyas well as anindexto access the items in a list.
A sorted list is a combination of an array and a hash table. It
contains a list of items that can be accessed using a key or an
index. If you access items using an index, it is an ArrayList, and if
you access items using a key , it is a Hashtable. The collection of
items is always sorted by the key value.

The SortedList class represents a collection of key-and-value pairs that are


sorted by the keys and are accessible by key and by index.
A sorted list is a combination of an array and a hash table. It contains a list of
items that can be accessed using a key or an index. If you access items using
an index, it is an ArrayList, and if you access items using a key, it is a
Hashtable. The collection of items is always sorted by the key value.

4. Stack
It represents alast-in, first outcollection of object.
It is used when you need a last-in, first-out access of items.
When you add an item in the list, it is calledpushingthe
item and when you remove it, it is calledpoppingthe item.

The Stack class represents alast-in-first-out (LIFO)Stack of Objects. Stack


follows the push-pop operations. That is we can Push (insert) Items into Stack and
Pop (retrieve) it back . Stack is implemented as a circular buffer. It follows the Last
In First Out (LIFO) system. That is we can push the items into a stack and get it in
reverse order. Stack returns the last item first. As elements are added to a Stack,
the capacity is automatically increased as required through reallocation.

Note:
Astackis a Last-InFirst-Out (LIFO) data
structure.
The last element added
to the queue will be the
first one to be removed.
The C language uses a
stack to store local data
in a function. The stack is
also used when
implementing
calculators.

1. The Push() method adds


an item at the top of the
stack.
2. The Pop() method
removes and returns the
item from the top of the
stack.
3. The Peek() method
returns the item from the
top of the stack.
It does not remove it.

5. Queue
It represents afirst-in, first outcollection of object.
It is used when you need a first-in, first-out access of
items. When you add an item in the list, it is
calledenqueueand when you remove an item, it is
calleddeque.

The Queue works likeFIFOsystem , afirst-in, first-outcollection of Objects. Objects


stored in a Queue are inserted at one end and removed from the other. The Queue
provide
additional
insertion,
extraction,
and
inspection
operations.
We
canEnqueue(add) items in Queue and we canDequeue(remove from Queue ) or we
can Peek (that is we will get the reference of first item ) item from Queue. Queue
accepts null reference as a valid value and allows duplicate elements. The first
element added to the queue will be the first one to be removed. Queues may be used
to process messages as they appear or serve customers as they come. The first
customer which comes should be served first.

6. BitArray
It represents an array of thebinary representationusing the
values 1 and 0.
It is used when you need to store the bits but do not know the
number of bits in advance. You can access items from the
BitArray collection by using aninteger index, which starts
from zero.

The BitArray class manages a compact array of bit values, which are represented as
Booleans, where true indicates that the bit is on (1) and false indicates the bit is off (0).
It is used when you need to store the bits but do not know the number of bits in
advance. You can access items from the BitArray collection by using an integer index,
which starts from zero.

You might also like