Learn step by step c# collections with easy examples. Learn generic, non-generic and specialized collections along with easy and great examples. Learn about arraylist, queue class,stack class and more. Difference between generic and non-generic collections. Difference between arraylist and simple ar...
Learn step by step c# collections with easy examples. Learn generic, non-generic and specialized collections along with easy and great examples. Learn about arraylist, queue class,stack class and more. Difference between generic and non-generic collections. Difference between arraylist and simple array.
Size: 268.34 KB
Language: en
Added: Oct 19, 2017
Slides: 33 pages
Slide Content
C# Collections By: Aijaz Ali Abro
A collection is a set of similarly typed objects that are grouped together. The principal benefit of collections is that they standardize the way groups of objects are handled by your programs. Collections are data structures that holds data in different ways for flexible operations . C# Collection classes are defined as part of the System. Collections or System.Collections.Generic namespace. What is a Collection ?
Most collection classes implement the same interfaces, and these interfaces may be inherited to create new collection classes that fit more specialized data storage needs.
Generic collections Non-Generic collections Specialized collections Types of Collections:
The System.Collections.Generic namespace contains interfaces and classes that define generic collections, which allow users to create strongly typed collections that provide better type safety and performance than non-generic strongly typed collections. Generic collections:
Fast lookups are critical. The Dictionary type provides fast lookups with keys to get values. With it we use keys and values of any type, including ints and strings. Dictionary Generic Class:
Dictionary<string, int> dictionary = new Dictionary<string, int>(); dictionary. Add("cat", 2); dictionary. Add("dog", 1); dictionary. Add("llama", 0); foreach (KeyValuePair<string, int> pair in dictionary) { Console.WriteLine("{0}, {1}", pair.Key, pair.Value); } OUTPUT: cat 2 dog 1 llama 0 A simple code example of Dictionary Generic Class :
Arrays do not dynamically resize. The List type does. With List, you do not need to manage the size on your own. This type is ideal for linear collections not accessed by keys. It provides many methods and properties. List Generic Class:
List<int > list = new List<int>(); list. Add(2); list. Add(3); list. Add(5); list. Add(7); foreach (int prime in list) { Console.WriteLine(prime); } OUTPUT: 2 3 5 7 A simple code example of List Generic Class :
Queue is a FIFO collection. It processes elements in a first-in, first-out order. To restate, it handles the elements that it received longest ago first. Queue is a generic type with one type parameter. Queue Generic Class:
Queue<string> numbers = new Queue<string>(); numbers.Enqueue("one"); numbers.Enqueue("two"); numbers.Enqueue("three"); foreach(string number in numbers ) { Console.WriteLine(number); } OUTPUT: one two three A simple code example of Queue Generic Class:
The Stack class represents a last-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. Stack Generic Class:
Stack<int> stack = new Stack <int>(); stack.Push(100); stack.Push(1000); stack.Push(10000); foreach (int i in stack) { Console.WriteLine(i); } OUTPUT: 10000 1000 100 A simple code example of Stack Generic Class:
NON-GENERIC CLASSES OR COLLECTIONS
The non-generic collections have been part of the .NET Framework since version 1.0. They are defined in the System.Collections namespace. The non-generic collections are general purpose data structures that operate on object references. Thus, they can manage any type of object, but not in a type-safe manner. This is both their advantage and disadvantage. Because they operate on object references, you can mix various types of data within the same collection. This makes them useful in situations in which you need to manage a collection of different types of objects or when the type of objects being stored are not known in advance. However, if you intend a collection to store a specific type of object, then the non-generic collections do not have the type-safety that is found in the generic collections. The non-generic collections are defined by a set of interfaces and the classes that implement those interfaces. NON-GENERIC defination :
System. Collections namespace define the following non-generic collection classes. The Non-Generic Collection Classes: Class Description ArrayList A dynamic array. This is an array that can grow as needed. Hashtable A hash table for key/value pairs. Queue A first-in, first-out list. SortedList A sorted list of key/value pairs. Stack A first-in, last-out list.
The ArrayList class supports dynamic arrays, which can grow or shrink as needed. An ArrayList is a variable-length array of object references that can dynamically increase or decrease in size. An ArrayList is created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array can be shrunk. ArrayList class:
using an arrayList and very easily we can add, insert , delete , Sort , view etc. It is very flexible because we can add without any size information , that is it will grow dynamically and also shrink.
Adding data / objects into ArrayList: ArrayList alist = new ArrayList(); alist.Add(“Aijaz Ali”); alist.Add(1345); alist.Add(1345.87); alist.Add(true); alist.Add(‘G’); Continue… ArrayList class Example:
Retrieve data using foreach loop: Syntax : foreach( dataType var in ArrayListRef ) { Console.WriteLine(var); } dataType // int , char , string , bool etc. var // int a , string name , bool b . In // keyword. ArrayListRef // ArrayList list = new ArrayList();
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. We can retrieve items from hashTable to provide the key . Both keys and values are Objects. HashTable Class:
Adding data / objects into HashTable : Hashtable weeks = new Hashtable(); weeks.Add("1", "Sunday"); weeks.Add("2", "Monday"); weeks.Add("3", "Tuesday"); weeks.Add("4", "Wed Day"); weeks.Add("5", "Thruway"); weeks.Add("6", "Friday"); weeks.Add("7", "Sat Day"); HashTable class Examples:
The Queue works like FIFO system , a first-in, first-out collection 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 can Enqueue (add) items in Queue and we can Dequeue (remove from Queue ). Queue Class :
Adding data / objects using Queue class : Queue days = new Queue(); days.Enqueue("Sunday"); days.Enqueue("Monday"); days.Enqueue("Tuesday"); days.Enqueue("Wednesday"); //Remove first object value “Sunday”. days.Dequeue (); Queue class Examples:
Foreach (string _names in days) { Console.WriteLine(_names); } OUTPUT: Monday Tuesday Wednesday Previous Example Output:
The Stack class represents a last-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. Stack Class :
Adding data / objects into Stack : Stack stack = new Stack(); stack.Push("Sunday"); stack.Push("Monday"); stack.Push(12345); stack.Push(1123.56); Console.WriteLine(stack.Pop ()); OUTPUT: 1123.56 Stack class Examples:
Non-Generic collections - These are the collections that can hold elements of different data types. It holds all elements as object type. So it includes overhead of type conversions ( overhead of implicit and explicit conversions). These are also called weakly typed. Generic collections - These are the collections that can hold data of same type and we can decide what type of data that collections can hold. These are also called strongly typed. Some advantages of generic collections - Type Safe, Secure, reduced overhead of type conversions. Difference between Between Generic & Non-Generic Collections:
Arrays are strongly typed. Array-Lists are not strongly typed. Elements in Arrays have to be of same data type (int, string, double, char, bool…). Elements in Array-List can have any type of data. Note: If Array-List has combined data types then type cast is must. Arrays are fixed specified length size therefore they cannot be resize dynamically during runtime. Difference between Array-List and a simple Array: