Application Development with .NET (31927) .NET Application Development (32998)
Lecture 9: Collections and Generics
Outline
• RichTextBox
• Collection Introduction • Non-Generic Collections • Generic Collections
RichTextbox Control
• RichTextBoxcontrolenablestodisplayoredittextcontentsincluding paragraphs, images, tables, etc.
• BothTextBoxandRichTextBoxallowsusertoedittext,butRichTextBox is preferred when text formatting is required along with images, tables, etc.
RichTextbox Control
Useful Properties of RichTextBox:
– SelectionFont: Gets or sets the font of the current text selection or insertion point. Useful for font related manipulations.
– Font: Gets or sets the font of the text displayed by the control.
– Text: Gets or sets the current text in the rich text box.
Useful methods of RichTextBox:
– Clear(): Clears all text from the text box control.
– Copy(): Copies the current selection in the text box to theClipboard.
– Cut(): Moves the current selection in the text box to theClipboard.
– Paste(): Replaces the current selection in the text box with the contents of the Clipboard.
Collections Introduction
• Collections are ways of storing retrieving data related data/objects.
• Collections are pre-packages data-structure classes- stores collections of data!
• Two ways:
• Create array of Objects : Fixed Size
• Create collections of Objects : Dynamically grow and shrink the group of objects
• The collection classes provide support for stacks, queues, lists, and hash tables.
• •
Collections Introduction
Different collections will have different performance properties. The C# language has two main type of collections:
• Non Generic (Standard) collections: Found under System.Collections namespace
• Class ArrayList
• Class Stack
• Class HashTable
• Class Queue
• Class SortedList
• Generic collections: Found under System.Collections.Generic namespace (preferred), added in the .Net FrameWork 2.0
• List
• Queue
• Stack
• SortedList
Collections Introduction
Common Features :
1. Allcollectionsprovidemethodsforadding,removingorfindingitemsin collections
2. AllcollectionsthatdirectlyorindirectlyimplementICollectioninterfaceor the ICollection
1. Ability to enumerate the collections
2. Ability to copy the collection contents in an array using the CopyTo method
3. Capacity (Number of elements it can contain) and Count (Actual number of elements) properties.
4. Consistent lower bound: index of its first element.
Collections Introduction
• All collection classes implement some combination of the collection interfaces given below:
Interface
Description
IEnumerable
Has GetEnumerator method which returns IEnumerable object.
ICollection
Contains a Count property and a CopyTo method to copy collection contents to an array. Implements IEnumerable
IList
Provides indexer for accessing specific elements in the collection. Also has Add, Remove, Contains and IndexOf methods. Inherits ICollection
IDictionary
Defines a collection of key/value pairs. Provides an indexer, methods for modifying (e.g. Add, Remove). Keys and Values properties. Inherits ICollection
How to Choose a Collection
Generic Collection
Non-Generic Collection
When to use
Dictionary
HashTable
Store items as key/value pairs for a quick look-up by key
List
Array ArrayList
Access items by index
Stack
Stack
Use item in Last-in First Out (LIFO) order
Queue
Queue
Use item in first-in-first-out (FIFO) order
LinkedList
Accessing items sequentially
Reference: https://docs.microsoft.com/en-us/dotnet/standard/collections/
Non-generic Collections
• These collections are found in System.Collections
• The collections store objects. Since all classes and structs are derived
from type object, using polymorphism, it can store any class and struct.
• A major disadvantage of these collections is that they are not type safe.
• The System.Collections namespace contains interfaces and classes that define various collections of objects, such as lists, queues, bit arrays, hash tables and dictionaries.
Non-generic Collections
• The following table lists some of the different types of collections in
System.Collections
Collection Class
Implements
Description
ArrayList
IList
Like an array but shrinks or grows as data is deleted or added
HashTable
IDictionary
An unordered collection of key/value pairs
Queue
ICollection
First in, first out collection
Stack
ICollection
Last in, first out collection
SortedList
IDictionary
A sorted list of key/value pairs
Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections?view=netframework-4.7.2
Non-generic Collections
• The following table lists some of the different types of collections interfaces in System.Collections
Collection Interfaces
Description
ICollection
Defines size, enumerators, and synchronization methods for all non-generic collections.
IList
Represents a non-generic collection of objects that can be individually accessed by index.
IDictionary
Represents a non-generic collection of key/value pairs
IEnumerable
Exposes an enumerator, which supports a simple iteration over a non-generic collection.
IEnumerator
Supports a simple iteration over a non-generic collection.
Non-generic Collections: HashTable Class
• HashTable in C# represents a collection of Key/Value pairs.
• Maps Keys Vales
• Any Non Null object can be used as a Key
• Items in a HashTable are retrieved by Keys
• Syntax:
Hashtable
Hashtable weekDays = new Hashtable();
Non-generic Collections: HashTable Class
• Common Properties and Methods:
Property
Description
Count
Gets the number of key-and-value pairs contained in the Hashtable.
Item
Gets or sets the value associated with the specified key.
Keys
Gets an ICollection containing the keys in the Hashtable.
Values
Gets an ICollection containing the values in the Hashtable.
IsFixed
Gets a value indicating whether the Hashtable has a fixed size.
Method
Description
public virtual void Add(object key, object value)
Gets the number of key-and-value pairs contained in the Hashtable.
public virtual void Clear()
Removes all elements from the Hashtable.
public virtual void Remove(object key)
Removes the element with the specified key from the Hashtable.
public virtual bool ContainsValue(object value)
Determines whether the Hashtable contains a specific value.
public virtual bool ContainsKey(object key)
Determines whether the Hashtable contains a specific key.
Non-generic Collections: HashTable Class
Example:
Output:
Non-generic Collections: Queue Class
Queue in C# represents a collection values arranged in First-in First-out order
Syntax:
Queue
Queue ticketNumber = new Queue();
Non-generic Collections: Queue Class
• Common Properties and Methods:
Property
Description
Count
Gets the number of key-and-value pairs contained in the Hashtable.
Method
Description
public virtual void Enqueue(object obj)
Adds an object to the end of the Queue.
public virtual void Clear()
Removes all elements from the Queue.
public virtual object Dequeue()
Removes and returns the object at the beginning of the Queue..
public virtual bool Contains (object value)
Determines whether an element is in the Queue.
public virtual object[] ToArray()
Copies the Queue to a new array
Non-generic Collections: Queue Class
Example:
Output:
Generic Collections
• Much better and type safe option for store and retrieve data
• Generic collection are available in the System.Collections.Generic
namespace
• The System.Collections.Generic contains interfaces and classes that define generic collections.
• The performance is better than the non-generic collections.
Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic?view=netframework-4.7.2
Generic Collections
• The following table lists some of the commonly used types of Generic collections in System.Collections.Generic
Collection Class
Description
LinkedList
Represents a doubly LinkedList
List
Represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists.
Queue
First in, first out generic collection
Stack
Last in, first out generic collection
Dictionary
Represents a collection of keys and values
Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic?view=netframework-4.7.2
Generic Collections
• The following table lists some of the commonly used types of Generic interfaces in System.Collections.Generic
Interface
Description
ICollection
Defines method to manipulate generic collections
IComparer
Defines a method that a type implements to compare two objects.
IDictionary
Represents a generic collection of key/value pairs.
IEnumerable
Exposes the enumerator, which supports a simple iteration over a collection of a specified type.
IEqualityComparer
Defines methods to support the comparison of objects for equality.
Ilist
Represents a collection of objects that can be individually accessed by index.
Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic?view=netframework-4.7.2
Generic Collections: Dictionary class
• Dictionary
1. Using the class:
Dictionary
IDictionary
IDictionary
Generic Collections: Dictionary class
• Common Properties and Methods:
Property
Description
Count
Gets the total number of elements exists in the Dictionary
Item
Gets or sets the element with the specified key in the Dictionary
Keys
Returns collection of keys of Dictionary
Values
Returns collection of values in Dictionary
Method
Description
Add(TKey, TValue)
Adds the specified key and value to the dictionary.
Clear()
Removes all keys and values from the Dictionary
Remove(TKey)
Removes the value with the specified key from the Dictionary
ContainsKey(TKey)
Determines whether the Dictionary
ContainsValue(TValue)
Determines whether the Dictionary
Generic Collections: Dictionary class
Output:
Generic Collections: LinkedList class
LinkedList
Syntax:
LinkedList
LinkedList
Generic Collections: LinkedList class
• Common Properties and Methods:
Property
Description
Count
Gets the number of nodes actually contained in the LinkedList
First
Gets the first node of the LinkedList
Last
Gets the last node of the LinkedList
Method
Description
AddAfter(LinkedListNode
Adds a new node containing the specified value after the specified existing node in the
LinkedList
AddBefore(LinkedListNode
Adds a new node containing the specified value before the specified existing node in the LinkedList
AddFirst(LinkedListNode
Adds the specified new node at the start of the LinkedList
AddLast(LinkedListNode
Adds the specified new node at the end of the LinkedList
Clear()
Removes all nodes from the LinkedList
Find(T)
Finds the first node that contains the specified value.
Generic Collections: LinkedList class
• Common Properties and Methods:
Method
Description
LinkedListNode
Find last occurrence of v
bool Remove(T v)
Remove the first occurrence of v. Return bool on success
void Remove(LinkedListNode
Remove n from list. Throws exception if not found
void removeFirst()
Removes first node in list
void RemoveLast()
Removes last node in list
Generic Collections: LinkedList class
Output: