Unit-2 Collection and Generic
Unit-2 Collection and Generic
C# Collection
C# collection types are designed to store, manage and manipulate similar data more efficiently.
Data manipulation includes adding, removing, finding, and inserting data in the collection.
Collection types implement the following common functionality:
Non-generic Generic
ArrayList -------------> List
HashTable -------------> Dictionary
1. Non-Generic
In non-generic collections, each element can represent a value of a different type. The collection size is
not fixed. Items from the collection can be added or removed at runtime.
● C# ArrayList (Non-Generic)
ArrayList class is a collection that can be used for any types or objects.
1. Arraylist is a class that is similar to an array, but it can be used to store values of various types.
2. An Arraylist doesn't have a specific size.
3. Any number of elements can be stored.
C# Collection
● C# HashTable (Non-generic)
HashTable is similar to arraylist but represents the items as a combination of a key and value.
Hashtable stores key and value pairs. It retrieves the values by comparing the hash value of the keys.
Hashtable ht = new Hashtable();
ht.Add("ora", "oracle");
ht.Add("vb", "vb.net");
ht.Add("cs", "cs.net");
ht.Add("asp", "asp.net");
foreach (DictionaryEntry d in ht)
{ Response.Write (d.Key + " " + d.Value);
Response.Write("<br>");
}
}
C# Collection
It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called
enqueue and when you remove an item, it is called deque.
The Queue<T> class in the System.Collection.Generic namespace represents a queue in C#, where T
specifies the type of elements in the queue.
QUEUE
string[] courses = {
"MCA",
"MBA",
"BCA",
"BBA",
"BTech",
"MTech"
};
Queue < string > queue1 = new Queue < string > ();
Queue < string > queue2 = new Queue < string > (courses);
Queue < string > queue3 = new Queue < string > (4);
Console.WriteLine("Number of elements in queue1:" + queue1.Count());
Console.WriteLine("Number of elements in queue2:" + queue2.Count());
Console.WriteLine("Number of elements in queue3:" + queue3.Count());
C# Collection
2. Generic Collection
Generic Collections work on the specific type that is specified in the program whereas non-generic collections
work on the object type.
1. Specific type
2. Array Size is not fixed
3. Elements can be added / removed at runtime.
List<T>
Creating a List
The List<T> is a generic collection, so you need to specify a type parameter for
the type of data it can store. The following example shows how to create list and
add elements.
LIST
// adding elements using add() method
var primeNumbers = new List<int>();
primeNumbers.Add(1);
primeNumbers.Add(3);
primeNumbers.Add(5);
primeNumbers.Add(7);
SortedList:
The SortedList<TKey, TValue>, and SortedList are collection classes that can
store key-value pairs that are sorted by the keys based on the associated IComparer
implementation. For example, if the keys are of primitive types, then sorted in
ascending order of keys.
Creating a Dictionary
You can create the Dictionary<TKey, TValue> object by passing the type of keys and values it can
store. The following example shows how to create a dictionary and add key-value pairs.
DICTIONARY
IDictionary<int, string> numberNames = new Dictionary<int, string>();
numberNames.Add(1,"One"); //adding key/value using the Add() method
numberNames.Add(3,"Three");
numberNames.Add(2,"Two");
foreach(KeyValuePair<int, string> kvp in numberNames)
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
//creating a dictionary using collection-initializer syntax
var cities = new Dictionary<string, string>(){
{"UK","London, Manchester, Birmingham"},
{"USA","Chicago, New York, Washington"},
{"India","Mumbai, New Delhi, Pune"}
};
foreach(var kvp in cities)
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
C# - Stack<T>
Stack is a special type of collection that stores elements in LIFO style (Last In First
Out). C# includes the generic Stack<T> and non-generic Stack collection classes. It is
recommended to use the generic Stack<T> collection.
Stack is useful to store temporary data in LIFO style, and you might want to delete an
element after retrieving its value.
C# - Stack<T>
Stack<T> Characteristics
● Stack<T> is Last In First Out collection.
● It comes under System.Collection.Generic namespace.
● Stack<T> can contain elements of the specified type. It provides compile-time type checking
and doesn't perform boxing-unboxing because it is generic.
● Elements can be added using the Push() method. Cannot use collection-initializer syntax.
● Elements can be retrieved using the Pop() and the Peek() methods. It does not support an
indexer.
C# - Stack<T>
Creating a Stack
You can create an object of the Stack<T> by specifying a type parameter for the type of
elements it can store. The following example creates and adds elements in the Stack<T>
using the Push() method. Stack allows null (for reference types) and duplicate values.
Note :
It is not required to use T as a type parameter. You can give any name to a type parameter. Generally, T is
used when there is only one type parameter. It is recommended to use a more readable type parameter
name as per requirement like TSession, TKey, TValue etc.
Generic Class
Example: Generic Class with Multiple Type Parameters :
Example 1 : Example 2:
static void Swap<T>(ref T lhs, ref T rhs) { public void AddOrUpdate(int index, T item)
{
T temp;
if(index >= 0 && index < 10)
temp = lhs; _data[index] = item;
lhs = rhs; }
rhs = temp;
public T GetData(int index) {
}
if(index >= 0 && index < 10)
return _data[index];
else return default(T);
} }
Example: Generic Method in Non-generic Class
C# Generic Constraints
Constraints inform the compiler about the capabilities a type argument must have. Without any
constraints, the type argument could be any type. The compiler can only assume the members of
System.Object, which is the ultimate base class for any .NET type.
If client code uses a type that doesn't satisfy a constraint, the compiler issues an error. Constraints
are specified by using the where contextual keyword.
C# allows you to use constraints to restrict client code to specify certain types while
instantiating generic types. It will give a compile-time error if you try to instantiate a generic
type using a type that is not allowed by the specified constraints.
Above, we applied the class constraint, which means only a reference type can be passed as an argument while
creating the DataStore class object. So, you can pass reference types such as class, interface, delegate, or
array type. Passing value types will give a compile-time error, so we cannot pass primitive data types or struct
types.
● LinkedList
● BitArray