C# Collections & Generics

Slides:



Advertisements
Similar presentations
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Advertisements

Chapter 24 Lists, Stacks, and Queues
AITI Lecture 19 Linked List Adapted from MIT Course 1.00 Spring 2003 Lecture 26 and Tutorial Note 9 (Teachers: Please do not erase the above note)
Lists, Stacks, Queues Svetlin Nakov Telerik Corporation
Generics, Lists, Interfaces
Fun with Lists for the Novice and Expert Scott Reed Brain Hz Software (760)
Data Structures and Collections
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
1 Chapter 24 Lists Stacks and Queues. 2 Objectives F To design list with interface and abstract class (§24.2). F To design and implement a dynamic list.
CS 307 Fundamentals of Computer Science 1 Abstract Data Types many slides taken from Mike Scott, UT Austin.
 2006 Pearson Education, Inc. All rights reserved Collections.
Collections. 2 Objectives Explore collections in System.Collections namespace –memory management –containment testing –sorting –traversal.
 2006 Pearson Education, Inc. All rights reserved Collections Many slides modified by Prof. L. Lilien (even many without an explicit message indicating.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 12 – Data Structures Outline 12.1Introduction.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 26 Implementing Lists, Stacks,
Stacks, Queues, and Deques
Lists, Stacks, Queues Svetlin Nakov Telerik Corporation
Collection types Collection types.
Maps A map is an object that maps keys to values Each key can map to at most one value, and a map cannot contain duplicate keys KeyValue Map Examples Dictionaries:
Comp 249 Programming Methodology Chapter 15 Linked Data Structure - Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
FEN 2012UCN Technology - Computer Science 1 Data Structures and Collections Principles revisited.NET: –Two libraries: System.Collections System.Collections.Generics.
Windows Programming Using C# Arrays, Collections.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 8 Stacks and Queues Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
Chapter 3 List Stacks and Queues. Data Structures Data structure is a representation of data and the operations allowed on that data. Data structure is.
Data Structures and Abstract Data Types "Get your data structures correct first, and the rest of the program will write itself." - David Jones.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Generics Collections. Why do we need Generics? Another method of software re-use. When we implement an algorithm, we want to re-use it for different types.
1/ 124 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 18 Programming Fundamentals using Java 1.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.
Evolution of.NET Collections (C#) Chen Dong
Data structures Abstract data types Java classes for Data structures and ADTs.
1 Chapter 17 Object-Oriented Data Structures. 2 Objectives F To describe what a data structure is (§17.1). F To explain the limitations of arrays (§17.1).
1/20/03A2-1 CS494 Interfaces and Collection in Java.
1 COMP3100e Developing Microsoft.Net Applications for Windows (Visual Basic.Net) Class 6 COMP3100E.
Generics Collections. Why do we need Generics? Another method of software re-use. When we implement an algorithm, we want to re-use it for different types.
Understanding Data Types and Collections Lesson 2.
AITI Lecture 18 Introduction to Data Structure, Stack, and Queue Adapted from MIT Course 1.00 Spring 2003 Lecture 23 and Tutorial Note 8 (Teachers: Please.
Interface: (e.g. IDictionary) Specification class Appl{ ---- IDictionary dic; dic= new XXX(); application class: Dictionary SortedDictionary ----
Advanced C#, part I Niels Hallenberg IT University of Copenhagen BAAAP – Spring 2009.
PROGRAMMING IN C#. Collection Classes (C# Programming Guide) The.NET Framework provides specialized classes for data storage and retrieval. These classes.
C# Collections & Generics C#.NET Software Development Version 1.0.
Session 07 Module 13 - Collections. Collections / Session 7 / 2 of 32 Review  A delegate in C# is used to refer to a method in a safe manner.  To invoke.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
1 Stacks (Continued) and Queues Array Stack Implementation Linked Stack Implementation The java.util.Stack class Queue Abstract Data Type (ADT) Queue ADT.
List Interface and Linked List Mrs. Furman March 25, 2010.
Object Oriented Software Development 6. Arrays and collections.
Data Structures and Collections Principles.NET: –Two libraries: System.Collections System.Collections.Generics FEN 2014UCN Teknologi/act2learn1 Deprecated.
Generics & Collection Classes Version 1.0. Topics Generic Methods and Classes Generic Collection Classes List Enumerators Queue Stack LinkedList.
1 Principles revisited.NET: Two libraries: System.Collections System.Collections.Generics Data Structures and Collections.
Collections Dwight Deugo Nesa Matic
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
Lecture 8: Collections, Comparisons and Conversions. Svetla Boytcheva AUBG, Spring COS 240 Object-Oriented Languages.
Module 5: Programming with C#. Overview Using Arrays Using Collections Using Interfaces Using Exception Handling Using Delegates and Events.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 2 nd Lecture Pavel Ježek
Collections ABCD ABCD Head Node Tail Node array doubly linked list Traditional Arrays and linked list: Below is memory representation of traditional.
Understanding Data Types and Collections Lesson 2.
Lecture 10 Collections Richard Gesick.
Sort & Search Algorithms
Advanced .NET Programming I 2nd Lecture
Computing with C# and the .NET Framework
Collections 24: Collections Programming C# © 2003 DevelopMentor, Inc.
structures and their relationships." - Linus Torvalds
CS313D: Advanced Programming Language
Fundaments of Game Design
Advanced .NET Programming I 3rd Lecture
Presentation transcript:

C# Collections & Generics C# .NET Software Development Version 1.1

Copyright 2012 by Dennis A. Fairclough all rights reserved. Overview Why Collections? Why Generic Datatypes? var data typing Collections C# 1.0 Style (object) Collections C# 2.0 Style (Generic) Collections C# 3.0 Initializers Collections C# 4.0 Dynamic Collections Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. Collections System.Collections Contain object references box and unbox value types as required Arrays, Linked Lists, Trees, Maps, etc. System.Collections.Generic Contains the appropriate data type Reduces problems with up/down casting Reduces boxing & unboxing overhead Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. var Keyword Used in classes, methods Compiler determines the appropriate type. Don’t use for common data types! Copyright 2012 by Dennis A. Fairclough all rights reserved.

Generics (C# Standard) Generics for classes, structs, methods interfaces, and Delegates (method pointers). Parameterized by the type of data they store and manipulate. Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. Generics C# generics will be immediately familiar to users of generics in Eiffel or Ada, Java or as templates to users of C++, though they do not suffer many of the complications of C++. Copyright 2012 by Dennis A. Fairclough all rights reserved.

Stack Example (double) public class RStack { private double[] _stack; private int _top; public int Top get { return _top; } set { _top = value; } } public RStack(int ssize) _stack = new double[ssize]; _top = 0; public void Push(double val) _stack[_top++] = val; public double Pop() return _stack[--_top]; }//END class RStack Copyright 2012 by Dennis A. Fairclough all rights reserved.

Stack Example (object ref) public class OStack { private object[] _stack; private int _top; public int Top get { return _top; } set { _top = value; } } public OStack(int ssize) _stack = new object[ssize]; _top = 0; public void Push(object val) _stack[_top++] = val; public object Pop() return _stack[--_top]; }//END class OStack Copyright 2012 by Dennis A. Fairclough all rights reserved.

Collections (object ref) Classes                                                                         Collections (object ref) Class Description ArrayList Implements the IList interface using an array whose size is dynamically increased as required. BitArray 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). CaseInsensitiveComparer Compares two objects for equivalence, ignoring the case of strings. CaseInsensitiveHashCodeProvider Supplies a hash code for an object, using a hashing algorithm that ignores the case of strings. CollectionBase Provides the abstract base class for a strongly typed collection. Comparer Compares two objects for equivalence, where string comparisons are case-sensitive. DictionaryBase Provides the abstract base class for a strongly typed collection of key/value pairs. Hashtable Represents a collection of key/value pairs that are organized based on the hash code of the key. Queue Represents a first-in, first-out collection of objects. ReadOnlyCollectionBase Provides the abstract base class for a strongly typed non-generic read-only collection. SortedList Represents a collection of key/value pairs that are sorted by the keys and are accessible by key and by index. Stack Represents a simple last-in-first-out (LIFO) non-generic collection of objects. Copyright 2012 by Dennis A. Fairclough all rights reserved.

Stack Example (generic) unbound type (“class Blueprint”) public class Stack<T> { private T[] _stack; private int _top; public int Top get { return _top; } set { _top = value; } } public Stack(int ssize) _stack = new T[ssize]; _top = 0; public void Push(T val) _stack[_top++] = val; public T Pop() return _stack[--_top]; }//END class Stack Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. Generic Methods public void Foo<T>(Stack<T> x,T val) { } Foo<double>(new Stack<double>(5),5.5); Copyright 2012 by Dennis A. Fairclough all rights reserved.

Generic Classes In General access_modifier class ident<T,K,..> { } generic datatype Copyright 2012 by Dennis A. Fairclough all rights reserved.

Collections (Generic) Description Comparer Provides a base class for implementations of the IComparer generic interface. Dictionary Represents a collection of keys and values. Dictionary.KeyCollection Represents the collection of keys in a Dictionary. This class cannot be inherited. Dictionary.ValueCollection Represents the collection of values in a Dictionary. This class cannot be inherited. EqualityComparer Provides a base class for implementations of the IEqualityComparer generic interface. KeyNotFoundException The exception that is thrown when the key specified for accessing an element in a collection does not match any key in the collection. LinkedList Represents a doubly linked list. LinkedListNode Represents a node in a LinkedList. This class cannot be inherited. List Represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists. Queue Represents a first-in, first-out collection of objects. SortedDictionary Represents a collection of key/value pairs that are sorted on the key. SortedDictionary.KeyCollection Represents the collection of keys in a SortedDictionary. This class cannot be inherited. SortedDictionary.ValueCollection Represents the collection of values in a SortedDictionary. This class cannot be inherited SortedList Represents a collection of key/value pairs that are sorted by key based on the associated IComparer implementation. Stack Represents a variable size last-in-first-out (LIFO) collection of instances of the same arbitrary type. Copyright 2012 by Dennis A. Fairclough all rights reserved.

Collection Interfaces IList : ICollection, IEnumerable IList<> ICollection : IEnumerable ICollection<> IDictionary : ICollection, IEnumerable IDictionary<> IEnumerable IEnumerable<> IEnumerator IEnumerator<> Copyright 2012 by Dennis A. Fairclough all rights reserved.

IList : ICollection, IEnumerable Add Clear Contains IndexOf Insert Remove RemoveAt Item (indexer) IsFixedSize IsReadOnly Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. ICollection Count (get only) IsSynchronized SyncRoot CopyTo Copyright 2012 by Dennis A. Fairclough all rights reserved.

Dictionary : ICollection,IEnumerable Add Clear Contains Remove Item (Indexer) Keys Values IsFixedSize IsReadOnly Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. IEnumerable GetEnumerator Allows use of foreach on a collection Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. IEnumerator Current MoveNext Reset (deprecated) Copyright 2012 by Dennis A. Fairclough all rights reserved.

Enumeration (Iterators) Enumeration refers to the process of iterating (stepping) through a collection Enumeration in C# actually implements a modification of the Iterator design pattern It’s called enumeration because as full-blown iteration saved for C# Version 2.0 yield break yield return Copyright 2012 by Dennis A. Fairclough all rights reserved.

The Iterator Design Pattern Collection class Nested Iterator class - knows enough about the collection to be able to expose one element of the at a time - Stores its current state Collection class exposes a way to create and initialize one or more iterator(s) Copyright 2012 by Dennis A. Fairclough all rights reserved.

Implementing an Enumerator A collection class implements IEnumerable interface Nested Enumerator class implements IEnumerator interface IEnumerable is required if you want to use foreach on your collection Unlike iterators, enumerators have the restriction that, if the collection changes, they become invalid You have to do this in your implementation C# Enumerators also restrict access through the enumerator to read-only   Name Description Current Gets the current element in the collection. MoveNext Advances the enumerator to the next element of the collection. Reset Sets the enumerator to its initial position, which is before the first element in the collection. Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. C# Collections General use: ArrayList and List<T> StringCollection HashTable and Dictionary<K, V> StringDictionary ListDictionary LinkedList<T> BitArray Hybrids: SortedList SortedDictionary HybridDictionary Specific Use: Queue Stack Copyright 2012 by Dennis A. Fairclough all rights reserved.

ArrayList and List<T> Linear array of objects Stored in contiguous memory Implements: IList ICollection IEnumerable ICloneable Resizes Dynamically Index into it like an array Elements must be added before they can be accessed (See ArrayList Demo) Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. Capacity Capacity – Gets or Sets the number of elements the ArrayList/List<T> can contain Count – Gets the number of elements the ArrayList/List<T> actually contains If Count == Capacity and you add 1 or more elements... A new array of twice the size is allocated The old elements are copied into the new location Expensive ! ! ! Set your Capacity upon creation if possible Default capacity is 4 Don’t change it once it is set It will change for you if it needs to Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. Adding elements ArrayList.Add(object obj) Appends the object to the end of the ArrayList ArrayList.AddRange(ICollection c) Appends a collection of objects to the end of the ArrayList ArrayList.Insert(int index, object obj) Inserts the object in the position indicated Has to move (copy) all subsequent elements ArrayList.InsertRange(int index, ICollection c) Inserts the a collection of objects in the position indicated Has to move all subsequent elements Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. Removing Elements ArrayList.Remove(object obj) Removes the first occurrence of obj ArrayList.RemoveAt(int index) Removes the item at the index indicated ArrayList.RemoveRange(int index, int count) Removes count items beginning at index ArrayList.Clear() Removes all the items from the ArrayList Be aware that removing from the middle (or the beginning) of an ArrayList will require moving all subsequent items. Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. Accessing elements Indexer Get and Set an item at the index indicated Returns an object (you must cast) ArrayList.GetRange(int index, int count) Returns a new ArrayList containing the elements from index for count ArrayList.ToArray() Builds a System.Array out of the array list ArrayList.Clone() Makes an exact (shallow) copy of the ArrayList Copyright 2012 by Dennis A. Fairclough all rights reserved.

Collection Initializers & Anonymous Types List<int> slist = new List<int>{0,1,2,3,4,5}; List<string> clist = new List<string> { new string(“szero”.ToCharArray()), new string(“stwo”.ToCharArray()), new string(“sthree”.ToCharArray()), new string(“sfour”.ToCharArray()), new string(“sfive”.ToCharArray()), } Anonymous Collection Type var temp = new {name="Dennis",number=100}; Copyright 2012 by Dennis A. Fairclough all rights reserved.

foreach on an ArrayList casts automatically Elements are read-only during the foreach ArrayList al = new ArrayList(9); // using Add and AddRange al.Add(0); al.Add(1); al.Add(2); al.Add(3); al.AddRange(new object[] {4, 5, 6, 7, 8}); foreach(int element in al) { Console.Write(element.ToString() + " "); } (Code is from ArrayList Demo) Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. Searching ArrayList.Contains(object item) Indicates whether the array list contains item Performs a linear search ArrayList.IndexOf(object item) Returns the index of the first occurrence of item in the ArrayList Returns -1 if the item is not found ArrayList.IndexOf(object item, int start) Returns the index of the first occurrence of item in the ArrayList after start Use this to search for all occurrences of an object ArrayList.BinarySearch(object item) Requires the ArrayList to be sorted If search fails, BinarySearch returns the inverse of the index of the next-largest item (or if there is no larger element, ArrayList.Count) O ( log (n) ) Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. Manipulating Items ArrayList.Reverse() Reverses the elements in the ArrayList ArrayList.Sort() Sorts the ArrayList Requires that all members implement IComparable ArrayList.Sort(IComparer comparer) Sorts the Arraylist Uses the comparer object instead of IComparable interface (if it existed) Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. New in List<T> Stupid name! AsReadOnly ConvertAll FindAll ForEach TrueForAll Copyright 2012 by Dennis A. Fairclough all rights reserved.

Specialization: StringCollection in System.Collections.Specialized An ArrayList wrapper specialized for strings In 2.0 we can just use List<string> Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. Searching and Sorting Use IComparable and/or IComparer Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. IComparable Required for binary searching and sorting Applies to items inside the Collection An item is said to be “Comparable” to another Comparable items inside a collection can be sorted and searched Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. IComparer Strategy Design Pattern Plug in a new comparer object for different results Can be applied to objects that are not “Comparable” Can be applied to override the comparable functionality that may already exist (See IComparableDemo ) Copyright 2012 by Dennis A. Fairclough all rights reserved.

Hashtable and Dictionary<K, V> A collection of Key-Value pairs Actually stored in a DictionaryEntry object Key cannot be null Value can be Implements IDictionary ICollection IEnumerable others Copyright 2012 by Dennis A. Fairclough all rights reserved.

Indexing into Hashtables Access into a Hashtable/Dictionary using an indexer: Hashtable ht = new Hashtable(); ht[“hello world”] = new MyObject(); Dictionary<string, MyObject> dict = new Dictionary<string, MyObject>(); dict["one"] = new MyObject(); Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. How hashing works... GetHashCode() is called on the key Keys are grouped into “buckets” This reduces the number of lookups needed to access Inside a bucket items are stored in a linear array If the maximum ratio of entries-to-buckets (called the load factor) is reached, more buckets are allocated and the entries are redistributed. (Expensive!) You may set the load factor when you create the Hashtable Default is 1.0 (an average of 1 item per bucket) Smaller load factor means faster lookups but take more memory Load factor values can be between .1 and 1.0 Copyright 2012 by Dennis A. Fairclough all rights reserved.

Indexing into a Hashtable Assignment: If the key does not exist, a new Dictionary entry is created If the key exists, the old value is overwritten Access: If the key does not exist, a KeyNotFoundException is thrown If the key exists, the value item is returned Hashtable ht = new Hashtable(); ht[“hello world”] = new MyObject(); Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. Add, Remove, Clear Add(object key, object value) Will add a new DictionaryEntry to the hashtable if key does not already exist If key exists, Add throws an InvalidArgument exception Remove(object key) Removes the corresponding dictionary entry if it exists Clear() Clears all DictionaryEntries from the Hashtable Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. Looking for items Contains(object key) ContiansKey(object key) Both functions act the same Includes Contains to satisfy IDictionary returns true if the Hashtable contains a corresponding DictionaryEntry O( 1 ) ContainsValue(object value) Searches all DictionaryEntries until it finds value or exhausts the Hashtable O ( n ) Copyright 2012 by Dennis A. Fairclough all rights reserved.

Symbol-Table Hashtable An example from a compiler Symbol-Table lookup: Hashtable table = new Hashtable(); ... table["if"] = new CToken("if", TokenType.If); table["elseif"] = new CToken("elseif", TokenType.ElseIf); table["else"] = new CToken("else", TokenType.Else); table["endif"] = new CToken("endif", TokenType.EndIf); table["for"] = new CToken("for", TokenType.For); table["foreach"] = new CToken("foreach", TokenType.Foreach); table["in"] = new CToken("in", TokenType.In); public CToken IdentifyNewToken(string lexeme) { if(table.Contains(lexeme)) return (GlobalTable[lexeme] as CToken); else return new CToken(); } Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. foreach on a Hashtable Remember, the Hashtable contains a collection of DictionaryEntry objects That being the case, this won’t work: You can do this: foreach(MyObject mo in _hashtable) { // work here } foreach(DictionaryEntry de in _hashtable) { MyObject mo = (MyObject)de.Value; // work here } foreach(var de in _hashtable) { var mo = de.Value; Copyright 2012 by Dennis A. Fairclough all rights reserved.

foreach on a Hashtable (continued) Or better yet: or: Note: order is not guaranteed foreach(MyObject mo in hashtable.Values) { // work here } foreach(MyObject mo in hashtable.Keys) { // work here } Copyright 2012 by Dennis A. Fairclough all rights reserved.

Keys and Values Properties An ICollection of the keys Values An ICollection of the values Order is not specified in either, except that it will be the same between them Items in these ICollections refer to the items in the Hashtable (they are shallow copies) Copyright 2012 by Dennis A. Fairclough all rights reserved.

Specialization: StringDictionary in System.Collections.Specialized Adapter Wrapper for a Hashtable exposing strings as the key and value In 2.0 use Dictionary<string, string> Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. ListDictionary Singly Linked-list key-value collection Faster than Hashtable for small collections (10 Items or less) Add, Remove, Search are all O(n) Implements IDictionary ICollection IEnumerable Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. LinkedList<T> Implements a doubly-linked list (finally!) Uses LinkedListNode<T> Fast insertion/removal Slow indexing (no indexer) Implements: ICollection IEnumerable Copyright 2012 by Dennis A. Fairclough all rights reserved.

LinkedList<T> Members Count First Last AddBefore AddAfter AddFirst AddLast Clear Contains Remove RemoveFirst RemoveLast RemoveBefore RemoveAfter Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. BitArray Compact storage for true/false values Stores in 32-bit chunks Bit-wise operations available and, or, not, xor Set(int index, bool value) SetAll(bool value) Use an indexer to access individual items Indexer returns a bool Implements ICollection IEnumerable ICloneable Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. Hybrid: SortedList A cross between a Hashtable and an ArrayList Stores DictionaryEntries in an array sorted by the key Indexing is not as fast as a hashtable Size is adjusted dynamically to meet capacity demands Indexer uses the key: mySortedList[myObject] = valueObject; To access by index, use GetByIndex(int index) and SetByIndex(int index, object value): mySortedList.SetByIndex(0, valueObject) Implements: IDictionary ICollection IEnumerable (See SortedList Demo) Copyright 2012 by Dennis A. Fairclough all rights reserved.

Hybrid: HybridDictionary Uses ListDictionary when small, Hashtable when large Moves items when the size increases Implements IDictionary ICollection IEnumerable Copyright 2012 by Dennis A. Fairclough all rights reserved.

Queue and Queue<T> Fifo data structure Dynamically resized to fit capacity requirements Implements: ICollection IEnumerable ICloneable Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. Manipulating a Queue Enqueue(object obj) Places obj at the end of the Queue Dequeue() Returns and removes the object at the front of the Queue Throws an InvalidOperationException if the Queue is empty Peek() Returns the object at the front of the Queue Clear() Empties the Queue Copyright 2012 by Dennis A. Fairclough all rights reserved.

Stack and Stack<T> Lifo data structure Dynamically resizes to meet capacity requirements Implements: ICollection IEnumerable ICloneable Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. Stack Manipulation Push(object obj) Puts obj on the top of the Stack Pop() Returns and removes the item from the top of the Stack Throws an InvalidOperationException if the Stack is empty Peek() Returns the top item from the Stack Clear() Clears all elements from the stack Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. CollectionBase Provided as an abstract base class for you to create your own collections Provides the virtual methods: Count Clear() RemoveAt() Provides a place to store your variables: InnerList – is an inherited member (protected) ArrayList Copyright 2012 by Dennis A. Fairclough all rights reserved.

SortedDictionary<K,V> Demo Code Copyright 2012 by Dennis A. Fairclough all rights reserved.

Copyright 2012 by Dennis A. Fairclough all rights reserved. What did you learn? ?? Copyright 2012 by Dennis A. Fairclough all rights reserved.