0% found this document useful (0 votes)
97 views

Unit-2 Collection and Generic

C# collection types allow storing and manipulating similar data efficiently. There are generic and non-generic collection types. Generic collections work with a specific data type while non-generic can hold different types. Common collection types include List, Dictionary, SortedList, Stack and Queue, with the generic versions generally preferred. List stores elements by index, Dictionary stores key-value pairs, and SortedList, Stack and Queue access elements in particular orders.

Uploaded by

Rahul Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
97 views

Unit-2 Collection and Generic

C# collection types allow storing and manipulating similar data efficiently. There are generic and non-generic collection types. Generic collections work with a specific data type while non-generic can hold different types. Common collection types include List, Dictionary, SortedList, Stack and Queue, with the generic versions generally preferred. List stores elements by index, Dictionary stores key-value pairs, and SortedList, Stack and Queue access elements in particular orders.

Uploaded by

Rahul Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

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:

● Adding and inserting items to a collection


● Removing items from a collection
● Finding, sorting, searching items
● Replacing items
● Copy and clone collections and items
● Capacity and Count properties to find the capacity of the collection and number of items in
the collection
C# Collection
Bounded Collection(Non-generic) and Unbounded
Collection(Generic Collection)
unbound generic type: A generic type declaration, by itself, denotes an unbound generic type ...
constructed type: A type that includes at least one type argument is called a constructed type.
open type: An open type is a type that involves type parameters.
closed type: A closed type is a type that is not an open type.
unbound type: refers to a nongeneric type or an unbound generic type.
bound type: refers to a nongeneric type or a constructed type….. nongeneric types are considered to be both bound and
unbound.

is below what I listed correct?


int //non-generic, closed, unbound & bound,
class A<T, U, V> //generic, open, unbound,
class A<int, U, V> //generic, open, bound, constructed
class A<int, int, V> //generic, open, bound, constructed
class A<int, int, int> //generic, closed, bound, constructed
C# Collection
.NET supports two types of collections, generic collections and non-generic collections.
Generic collections with work generic data type. Learn more about generics here: Generics in C#.

The following table lists and matches these classes.

Non-generic Generic
ArrayList -------------> List
HashTable -------------> Dictionary

SortedList -------------> SortedList


Stack -------------> Stack
Queue -------------> Queue
C# Collection
● Arrays
Array class is defined in System namespace. Arrays can store any type of data but only one type at
a time. The size of the array has to be specified at compilation time. Insertion and deletion reduce
performance
● Advanced Collections
Many times we can’t give number elements in the list and we need to perform different operations
like inserting, deleting, sorting, searching, comparing, and so on. To perform these operations
efficiently, the data needs to be organized in a specific way. This gives rise to advanced collections.
Advanced collections are found in System.Collections namespace.
C# Collection

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

● C# SortedList (Generic as well as Non-generic)


SortedList class is a collection of (key, value) pairs which are sorted according to keys. Those pairs can be
accessible by key and as well as by index(zero-based indexing). This comes under System.Collections
namespace.
It is of both generic and non-generic type of collection. The generic SortedList is defined in
System.Collections.Generic namespace whereas non-generic SortedList is defined under System.Collections
namespace.

1. Is a class that has the combination of arraylist and hashtable.


2. Represents the data as a key and value pair.
3. Arranges all the items in sorted order.
SortedList
● The SortedList class implements the IEnumerable, ICollection, IDictionary and ICloneable interfaces.
● In SortedList, an element can be accessed by its key or by its index.
● A SortedList object internally maintains two arrays to store the elements of the list, i.e, one array for the keys
and another array for the associated values.
● Here, a key cannot be null, but a value can be.
● The capacity of a SortedList object is the number of key/value pairs it can hold.
● In SortedList, duplicate keys are not allowed.
● In SortedList, you can store values of the same type and of the different types due to the non-generic
collection. If you use a generic SortedList in your program, then it is necessary that the type of the values
should be the same.
● In SortedList you cannot store keys of different data types in the same SortedList because the compiler will
throw an exception. So, always add the key in your SortedList of the same type.
● You can also cast key/value pair of SortedList into DictionaryEntry.
Exception

//The following will throw exceptions //


numberNames.Add("Three", 3); //Compile-time error: key must be
int type
numberNames.Add(1, "One"); //Run-time exception: duplicate key
numberNames.Add(null, "Five");//Run-time exception: key cannot
be null
C# Collection
● Stack: (Generic as well as Non-generic)
A stack is a LIFO (last in first out) data structure. Think of stack as a collection of items where anything
you insert in a stack will be placed at the top and if you need to remove something, it will be removed from
the top. A stack of plates or a book stack are two common examples of a stack.

It uses a key as well as an index to 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 Stack<T> is a collection that is defined in the System.Collection.Generic namespace where T
specified the type of elements in the stack.
C# Collection

● Queue (Generic as well as Non-generic)


A Queue represents a first-in, first-out (FIFO) collection of objects. An example of a queue is a line of
people waiting.

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.

Generic Collection includes :

List, Dictionary, SortedList, Stack, Queue


Generic Collection (List, Dictionary, SortedList, Stack, Queue)

List<T>

The List<T> is a collection of strongly typed objects that can be accessed by


index and having methods for sorting, searching, and modifying list. It is the
generic version of the ArrayList that comes under System.Collection.Generic
namespace.

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);

Console.WriteLine("No of elelemts: "+ primeNumbers.Count);

var cities = new List<string>();


cities.Add("New York");
cities.Add("London");
cities.Add("Mumbai");
cities.Add("Chicago");
cities.Add(null); // null is allowed

Console.WriteLine("No of elelemts: " + cities.Count);


Generic Collection (List, Dictionary, SortedList, Stack, Queue)

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.

C# supports generic and non-generic SortedList. It is recommended to use generic


SortedList<TKey, TValue> because it performs faster and less error-prone than the
non-generic SortedList.
C# - Dictionary<TKey, TValue>
In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of
Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type.
Dictionary is defined under System.Collection.Generic namespace. It is dynamic in nature means the size
of the dictionary is grows according to the need.Dictionary Characteristics

● Dictionary<TKey, TValue> stores key-value pairs.


● Comes under System.Collection.Generic namespace.
● Implements IDictionary<TKey, TValue> interface.
● Keys must be unique and cannot be null.
● Values can be null or duplicate.
● Values can be accessed by passing associated key in the indexer e.g. myDictionary[key]
● Elements are stored as KeyValuePair<TKey, TValue> objects.
C# - Dictionary<TKey, TValue>

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.

Example: Create and Add Elements in Stack


Stack<int> myStack = new Stack<int>();
myStack.Push(1);
myStack.Push(2);
myStack.Push(3);
myStack.Push(4);
foreach (var item in myStack) Console.Write(item + ","); //prints 4,3,2,1,
Generics
● C# allows you to define generic classes, interfaces, abstract classes, fields, methods,
static methods, properties, events, delegates, and operators
● Using the type parameter and without the specific data type.
● A type parameter is a placeholder for a particular type specified when creating an
instance of the generic type.
● A generic type is declared by specifying a type parameter in an angle brackets after a
type name,
● e.g. TypeName<T> where T is a type parameter.
● Generic types perform better than normal system types because they reduce the
need for boxing, unboxing, and type casting the variables or objects.
Generic Class
Generic classes are defined using a type parameter in an angle brackets after the class name. The
following defines a generic class :

class DataStore<T> { public T Data { get; set; } }

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 :

class KeyValuePair<TKey, TValue> {


public TKey Key { get; set; } // acc-specifier typeparameter property_name
public TValue Value { get; set; }
}

Instantiating Generic Class :


You can create an instance of generic classes by specifying an actual type in angle brackets. The
following creates an instance of the generic class DataStore.

DataStore<string> store = new DataStore<string>()


Generic Class
.

DataStore<string> store = new DataStore<string>();


store.Data = "Hello World!";
// store.Data = 123; //compile-time error
Generic Class
DataStore<string> strStore = new DataStore<string>();
strStore.Data = "Hello World!";
//strStore.Data = 123; // compile-time error

DataStore<int> intStore = new DataStore<int>();


intStore.Data = 100;
//intStore.Data = "Hello World!"; // compile-time error

KeyValuePair<int, string> kvp1 = new KeyValuePair<int, string>();


kvp1.Key = 100;
kvp1.Value = "Hundred";

KeyValuePair<string, string> kvp2 = new KeyValuePair<string, string>();


kvp2.Key = "IT";
kvp2.Value = "Information Technology";
Generic Class Characteristics
● A generic class increases the reusability. The more type parameters mean more reusable it
becomes. However, too much generalization makes code difficult to understand and maintain.
● A generic class can be a base class to other generic or non-generic classes or abstract
classes.
● A generic class can be derived from other generic or non-generic interfaces, classes, or
abstract classes.
● You can create your own generic interfaces, classes, methods, events, and delegates.
● You may create generic classes constrained to enable access to methods on particular data
types.
● You may get information on the types used in a generic data type at run-time by means of
reflection.
Generic Methods
A method declared with the type parameters for its return type or parameters is called a generic
method.

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.

GenericTypeName<T> where T : contraint1, constraint2


C# Generic Constraints
Example: Declare Generic Constraints
class DataStore<T> where T : class
{ public T Data
{ get; set; } }

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.

DataStore<string> store = new DataStore<string>();


DataStore<MyClass> store = new DataStore<MyClass>();
DataStore<IMyInterface> store = new DataStore<IMyInterface>();
DataStore<IEnumerable> store = new DataStore<IMyInterface>();
DataStore<ArrayList> store = new DataStore<ArrayList>();
DataStore<int> store = new DataStore<int>();
where T : struct
The following example demonstrates the struct constraint that restricts type argument to be
non-nullable value type only.

class DataStore<T> where T : struct


{ public T Data { get; set; } }

DataStore<int> store = new DataStore<int>(); // valid


DataStore<char> store = new DataStore<char>(); // valid
DataStore<MyStruct> store = new DataStore<MyStruct>(); // valid

//DataStore<string> store = new DataStore<string>(); // compile-time error


//DataStore<IMyInterface> store = new DataStore<IMyInterface>(); // compile-time error
//DataStore<ArrayList> store = new DataStore<ArrayList>(); // compile-time error
where T : new()
The following example demonstrates the struct constraint that restricts type argument to be
non-nullable value type only.

class DataStore<T> where T : class, new()


{ public T Data { get; set; } }

DataStore<MyClass> store = new DataStore<MyClass>(); // valid


DataStore<ArrayList> store = new DataStore<ArrayList>(); // valid

//DataStore<string> store = new DataStore<string>(); // compile-time error //DataStore<int> store = new


DataStore<int>(); // compile-time error //DataStore<IMyInterface> store = new DataStore<IMyInterface>(); //
compile-time error
where T : baseclass
The following example demonstrates the base class constraint that restricts type argument to be a
derived class of the specified class, abstract class, or an interface.

class DataStore<T> where T : IEnumerable


{ public T Data { get; set; } }
DataStore<ArrayList> store = new DataStore<ArrayList>(); // valid
DataStore<List> store = new DataStore<List>(); // valid

//DataStore<string> store = new DataStore<string>(); // compile-time error


//DataStore<int> store = new DataStore<int>(); // compile-time error
//DataStore<IMyInterface> store = new DataStore<IMyInterface>(); // compile-time error
//DataStore<MyClass> store = new DataStore<MyClass>(); // compile-time error
Self Study

● LinkedList
● BitArray

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy