59
sheepsqueezers.com Copyright ©2011 sheepsqueezers.com C# Programming IV-2: System.Collections Namespace

dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com

C# Programming IV-2: System.Collections Namespace

Page 2: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com

This work may be reproduced and redistributed, in whole or in part, without alteration and without prior written permission, provided all copies contain the following statement:

Copyright ©2011 sheepsqueezers.com. This

work is reproduced and distributed with the

permission of the copyright holder.

Legal Stuff

This presentation as well as other presentations and documents found on the sheepsqueezers.com website may contain quoted material from outside sources such as books, articles and websites. It is our intention to diligently reference all outside sources. Occasionally, though, a reference may be missed. No copyright infringement whatsoever is intended, and all outside source materials are copyright of their respective author(s).

Page 3: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com

.NET Lecture Series

C# Programming V:

Introduction to LINQ

C# Programming I: Concepts of OOP

C# Programming II:

Beginning C#

C# Programming III:

Advanced C#

C# Programming IV-1:

System Namespace

C# Programming IV-2: System.Collections

Namespace

C# Programming IV-3: System.Collections.

Generic Namespace

C# Programming IV-4A:

System.Data Namespace

C# Programming IV-4B: System.Data.Odbc

Namespace

C# Programming IV-4C: System.Data.OleDb

Namespace

C# Programming IV-4E:

System.Data.SqlClient Namespace

C# Programming IV-4F:

System.Data.SqlTypes Namespace

C# Programming IV-5:

System.Drawing/(2D) Namespace

C# Programming IV-7: System.Numerics

C# Programming IV-6:

System.IO Namespace

C# Programming IV-8: System.Text and

System.Text. RegularExpressions

Namespaces

C# Programming IV-4D:

Oracle.DataAccess.Client Namespace

C#

Self-Inflicted

Project #1

Address

Cleaning

C#

Self-Inflicted

Project #2

Large

Intersection Problem

Page 4: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Charting Our Course The System.Collections Namespace

What Next?

Page 5: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

The System.Collections Namespace

The System.Collections Namespace is defined by Microsoft as follows:

The System.Collections namespace contains interfaces and classes that define various collections of objects, such as lists, queues, bit arrays, hash tables and dictionaries.

Note that some authors recommend that you always use the System.Collections.Generic namespace instead of this one. Please see the presentation on System.Collections.Generic for more information.

Page 6: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

The System.Collections Namespace

Classes

ArrayList

Page 7: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

ArrayList

The ArrayList class implements the IList interface using an array whose size

is dynamically increased as required. According to Microsoft's website: The ArrayList is not guaranteed to be sorted. You must sort the ArrayList prior to performing operations (such as BinarySearch) that require the ArrayList to be sorted. The capacity of a ArrayList is the number of elements the ArrayList can hold. As elements are added to an ArrayList, the capacity is automatically increased as required through reallocation. The capacity can be decreased by calling TrimToSize or by setting the Capacity property explicitly. Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based. The ArrayList collection accepts null as a valid value, allows duplicate elements. Using multidimensional arrays as elements in an ArrayList collection is not supported.

Constructors • ArrayList() - Initializes a new instance of the ArrayList class that is empty and has the default initial capacity.

• ArrayList(ICollection) - Initializes a new instance of the ArrayList class that contains elements copied from the specified collection and that has the same initial capacity as the number of elements copied.

• ArrayList(Int32) - Initializes a new instance of the ArrayList class that is empty and has the specified initial capacity.

Properties • Capacity - Gets or sets the number of elements that the ArrayList can contain.

• Count - Gets the number of elements actually contained in the ArrayList.

• IsFixedSize - Gets a value indicating whether the ArrayList has a fixed size.

• IsReadOnly - Gets a value indicating whether the ArrayList is read-only.

• IsSynchronized - Gets a value indicating whether access to the ArrayList is synchronized (thread safe).

• Item - Gets or sets the element at the specified index.

• SyncRoot - Gets an object that can be used to synchronize access to the ArrayList.

Page 8: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

ArrayList

Methods • Adapter - Creates an ArrayList wrapper for a specific IList.

• Add - Adds an object to the end of the ArrayList.

• AddRange - Adds the elements of an ICollection to the end of the ArrayList.

• BinarySearch(Object) - Searches the entire sorted ArrayList for an element using the default comparer and returns the zero-based index of the element.

• BinarySearch(Object, IComparer) - Searches the entire sorted ArrayList for an element using the specified comparer and returns the zero-based index of the element.

• BinarySearch(Int32, Int32, Object, IComparer) - Searches a range of elements in the sorted ArrayList for an element using the specified comparer and returns the zero-based index of the element.

• Clear - Removes all elements from the ArrayList.

• Clone - Creates a shallow copy of the ArrayList.

• Contains - Determines whether an element is in the ArrayList.

• CopyTo(Array) - Copies the entire ArrayList to a compatible one-dimensional Array, starting at the beginning of the target array.

• CopyTo(Array, Int32) - Copies the entire ArrayList to a compatible one-dimensional Array, starting at the specified index of the target array.

• CopyTo(Int32, Array, Int32, Int32) - Copies a range of elements from the ArrayList to a compatible one-dimensional Array, starting at the specified index of the target array.

• Equals(Object) - Determines whether the specified Object is equal to the current Object. (Inherited from Object.)

• Finalize - Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)

• FixedSize(ArrayList) - Returns an ArrayList wrapper with a fixed size.

• FixedSize(IList) - Returns an IList wrapper with a fixed size.

• GetEnumerator() - Returns an enumerator for the entire ArrayList.

• GetEnumerator(Int32, Int32) - Returns an enumerator for a range of elements in the ArrayList.

• GetHashCode - Serves as a hash function for a particular type. (Inherited from Object.)

• GetRange - Returns an ArrayList which represents a subset of the elements in the source ArrayList.

• GetType - Gets the Type of the current instance. (Inherited from Object.)

• IndexOf(Object) - Searches for the specified Object and returns the zero-based index of the first occurrence within the entire ArrayList.

• IndexOf(Object, Int32) - Searches for the specified Object and returns the zero-based index of the first occurrence within the range of elements in the ArrayList that extends from the specified index to the last element.

• IndexOf(Object, Int32, Int32) - Searches for the specified Object and returns the zero-based index of the first occurrence within the range of elements in the ArrayList that starts at the specified index and contains the specified number of elements.

Page 9: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

ArrayList

Methods • Insert - Inserts an element into the ArrayList at the specified index.

• InsertRange - Inserts the elements of a collection into the ArrayList at the specified index.

• LastIndexOf(Object) - Searches for the specified Object and returns the zero-based index of the last occurrence within the entire ArrayList.

• LastIndexOf(Object, Int32) - Searches for the specified Object and returns the zero-based index of the last occurrence within the range of elements in the ArrayList that extends from the first element to the specified index.

• LastIndexOf(Object, Int32, Int32) - Searches for the specified Object and returns the zero-based index of the last occurrence within the range of elements in the ArrayList that contains the specified number of elements and ends at the specified index.

• MemberwiseClone - Creates a shallow copy of the current Object. (Inherited from Object.)

• ReadOnly(ArrayList) - Returns a read-only ArrayList wrapper.

• ReadOnly(IList) - Returns a read-only IList wrapper.

• Remove - Removes the first occurrence of a specific object from the ArrayList.

• RemoveAt - Removes the element at the specified index of the ArrayList.

• RemoveRange - Removes a range of elements from the ArrayList.

• Repeat - Returns an ArrayList whose elements are copies of the specified value.

• Reverse() - Reverses the order of the elements in the entire ArrayList.

• Reverse(Int32, Int32) - Reverses the order of the elements in the specified range.

• SetRange - Copies the elements of a collection over a range of elements in the ArrayList.

• Sort() - Sorts the elements in the entire ArrayList.

• Sort(IComparer) - Sorts the elements in the entire ArrayList using the specified comparer.

• Sort(Int32, Int32, IComparer) - Sorts the elements in a range of elements in ArrayList using the specified comparer.

• Synchronized(ArrayList) - Returns an ArrayList wrapper that is synchronized (thread safe).

• Synchronized(IList) - Returns an IList wrapper that is synchronized (thread safe).

• ToArray() - Copies the elements of the ArrayList to a new Object array.

• ToArray(Type) - Copies the elements of the ArrayList to a new array of the specified element type.

• ToString - Returns a string that represents the current object. (Inherited from Object.)

• TrimToSize - Sets the capacity to the actual number of elements in the ArrayList.

Page 10: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

ArrayList

If you take a look at the Sort method for an ArrayList, you will see that one of the overloads accepts an IComparer interface allowing you to sort the Arraylist

based on your own specialized type of sort. This interface, which is located within the System.Collections namespace, contains the signature for a single method: Compare(Object x, Object y). This method must return the

following values in order for your "special" sort to work:

• less than zero indicates "x is less than y"

• zero indicates "x equals y"

• greater than zero indicates "x is greater than y"

A simple example follows below and on the next slide:

using System;

using System.Collections;

using System.ComponentModel;

//Create a class to hold the Compare method and the eSpectrumOrder enumeration.

public class SpectrumSortClass : IComparer {

enum eSpectrumOrder {violet=1, blue, cyan, green, yellow, orange, red};

//Create the Compare method

public Int32 Compare(Object oColorX, Object oColorY) {

//For oColorX and oColorY, pull their enumeration value from eSpectrumOrder

Int32 iColorX = (Int32)TypeDescriptor.GetConverter(typeof(eSpectrumOrder)).ConvertFromString((String) oColorX);

Int32 iColorY = (Int32)TypeDescriptor.GetConverter(typeof(eSpectrumOrder)).ConvertFromString((String) oColorY);

return ( Math.Sign(iColorX - iColorY) );

}

}

…continued on next slide…

Page 11: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

ArrayList

class MainProgram {

public static void Main() {

//Given an array of spectrum colors, order them based on the eSpectrumOrder and not alphabetical order!

ArrayList alColors = new ArrayList();

//Create an variable that points to our SpectrumSortClass with our Compare method

IComparer interfaceCompare = new SpectrumSortClass();

//Load the array with colors not necessarily in spectrum order.

alColors.Add("green");

alColors.Add("blue");

alColors.Add("violet");

alColors.Add("yellow");

alColors.Add("cyan");

alColors.Add("red");

alColors.Add("orange");

alColors.Add("violet");

alColors.Add("blue");

//Sort our array in spectrum-color order.

alColors.Sort(interfaceCompare);

//Display each color in spectrum-sorted order.

foreach(String sColor in alColors) {

Console.WriteLine(sColor);

}

}

}

The output is shown below(transposed to save space):

violet violet blue blue cyan green yellow orange red

Page 12: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Classes

BitArray

The System.Collections Namespace

Page 13: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

BitArray

The BitArray class 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). According to Microsoft's website: The size of a BitArray is controlled by the client; indexing past the end of the BitArray throws an ArgumentException. Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based.

Constructors • BitArray(BitArray) - Initializes a new instance of the BitArray class that contains bit values copied from the specified BitArray.

• BitArray(Boolean[]) - Initializes a new instance of the BitArray class that contains bit values copied from the specified array of Booleans.

• BitArray(Byte[]) - Initializes a new instance of the BitArray class that contains bit values copied from the specified array of bytes.

• BitArray(Int32) - Initializes a new instance of the BitArray class that can hold the specified number of bit values, which are initially set to false.

• BitArray(Int32[]) - Initializes a new instance of the BitArray class that contains bit values copied from the specified array of 32-bit integers.

• BitArray(Int32, Boolean) - Initializes a new instance of the BitArray class that can hold the specified number of bit values, which are initially set to the specified value.

Properties • Count - Gets the number of elements contained in the BitArray.

• IsReadOnly - Gets a value indicating whether the BitArray is read-only.

• IsSynchronized - Gets a value indicating whether access to the BitArray is synchronized (thread safe).

• Item - Gets or sets the value of the bit at a specific position in the BitArray.

• Length - Gets or sets the number of elements in the BitArray.

• SyncRoot - Gets an object that can be used to synchronize access to the BitArray.

Page 14: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

BitArray

Methods • And - Performs the bitwise AND operation on the elements in the current BitArray against the corresponding elements in the

specified BitArray.

• Clone - Creates a shallow copy of the BitArray.

• CopyTo - Copies the entire BitArray to a compatible one-dimensional Array, starting at the specified index of the target array.

• Equals(Object) - Determines whether the specified Object is equal to the current Object. (Inherited from Object.)

• Finalize - Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)

• Get - Gets the value of the bit at a specific position in the BitArray.

• GetEnumerator - Returns an enumerator that iterates through the BitArray.

• GetHashCode - Serves as a hash function for a particular type. (Inherited from Object.)

• GetType - Gets the Type of the current instance. (Inherited from Object.)

• MemberwiseClone - Creates a shallow copy of the current Object. (Inherited from Object.)

• Not - Inverts all the bit values in the current BitArray, so that elements set to true are changed to false, and elements set to false are changed to true.

• Or - Performs the bitwise OR operation on the elements in the current BitArray against the corresponding elements in the specified BitArray.

• Set - Sets the bit at a specific position in the BitArray to the specified value.

• SetAll - Sets all bits in the BitArray to the specified value.

• ToString - Returns a string that represents the current object. (Inherited from Object.)

• Xor - Performs the bitwise exclusive OR operation on the elements in the current BitArray against the corresponding elements in the specified BitArray.

Have you ever had to compute the values needed to display a Venn Diagram? For example, let's say that you are given three datasets (that is, database tables). Each dataset represents a credit card like Mastercard, Discover and American Express. Now, each dataset has one column in it: Customer_Id. In order to compute the values for your Venn Diagram, you compute the intersection of datasets two at a time by joining by Customer_Id. The number of values in the intersection is the value that represents that portion of the Venn Diagram. Now, we talked about an easy way to compute this information in one

Page 15: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

BitArray

of my other presentations, so we won't talk about that here. But, it seems like you could achieve something similar using a BitArray and the And, Or and Xor

methods available to you. For example, assume that our three datasets contain a total of 10 unique Customer_Ids. There may only be, say, 5 customers in the American Express table, 4 in the Discover dataset and 2 in the Mastercard dataset, but there are 10 unique Customer_Ids. Now, let's also assume, without loss of generality (I've always wanted to say that!!) that our Customer_Ids are numbered from 1 to 10. Below, we create three BitArrays (to represent the

three credit cards) containing 10 slots all initially set to false. We then update each BitArray based on that credit card's Customer_Ids. We then find the intersection of each and then count the number of trues.

using System;

using System.Collections;

class MainProgram {

public static Int32 BitCount(BitArray pbaINPUT) {

Int32 iCount = 0;

for(Int32 indx=0; indx<pbaINPUT.Length; indx++) {

if ( pbaINPUT.Get(indx) ) {

iCount++;

}

}

return(iCount);

}

…continued on next slide..

Page 16: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

BitArray

public static void Main() {

BitArray baMSTR = new BitArray(10,false); //Assume 10 total unique customers

BitArray baDISC = new BitArray(10,false); //Assume 10 total unique customers

BitArray baAMEX = new BitArray(10,false); //Assume 10 total unique customers

BitArray baRESULTS = new BitArray(10,false); //This will hold the intersection results.

//Below are arrays of customer IDs presumably pulled from the database.

Int32[] aCUSTID_MSTR = new Int32[7] {1,2,3,4,5,8,9};

Int32[] aCUSTID_DISC = new Int32[6] {0,2,4,6,8,9};

Int32[] aCUSTID_AMEX = new Int32[4] {1,3,6,8};

//Update the BitArrays based on each Int32 array above.

for(Int32 indx=0;indx<aCUSTID_MSTR.Length;indx++) {

baMSTR.Set(aCUSTID_MSTR[indx],true);

}

for(Int32 indx=0;indx<aCUSTID_DISC.Length;indx++) {

baDISC.Set(aCUSTID_DISC[indx],true);

}

for(Int32 indx=0;indx<aCUSTID_AMEX.Length;indx++) {

baAMEX.Set(aCUSTID_AMEX[indx],true);

}

//Next, perform the intersections.

baRESULTS = (BitArray) baMSTR.Clone();

baRESULTS.And(baDISC);

Console.WriteLine("Number of customers who have a Master Card and a Discover

card={0}",BitCount(baRESULTS));

…continued on next slide…

Page 17: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

BitArray

baRESULTS = (BitArray) baMSTR.Clone();

baRESULTS.And(baAMEX);

Console.WriteLine("Number of customers who have a Master Card and a American Express

card={0}",BitCount(baRESULTS));

baRESULTS = (BitArray) baDISC.Clone();

baRESULTS.And(baAMEX);

Console.WriteLine("Number of customers who have a Discover card and a American Express

card={0}",BitCount(baRESULTS));

baRESULTS = (BitArray) baMSTR.Clone();

baRESULTS.And(baDISC).And(baAMEX);

Console.WriteLine("Number of customers who all three cards={0}",BitCount(baRESULTS));

}

}

Note that I am using the Clone method to create a copy of the BitArray to the left of the And method. The reason is because the And method is volatile and will replace the BitArray on the left of the And with the results of the And method!! That is, baLEFT.And(baRIGHT); will overwrite baLEFT with the results of the And!! Be careful!!

The results are below:

Number of customers who have a Master Card and a Discover card=4

Number of customers who have a Master Card and a American Express card=3

Number of customers who have a Discover card and a American Express card=2

Number of customers who all three cards=1

Page 18: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Classes

CaseInsensitiveComparer

The System.Collections Namespace

Page 19: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

CaseInsensitiveComparer

The CaseInsensitiveComparer class compares two objects for equivalence,

ignoring the case of strings.

Constructors • CaseInsensitiveComparer() - Initializes a new instance of the CaseInsensitiveComparer class using the Thread.CurrentCulture

of the current thread.

• CaseInsensitiveComparer(CultureInfo) - Initializes a new instance of the CaseInsensitiveComparer class using the specified System.Globalization.CultureInfo.

Properties • Default - Gets an instance of CaseInsensitiveComparer that is associated with the Thread.CurrentCulture of the current thread

and that is always available.

• DefaultInvariant - Gets an instance of CaseInsensitiveComparer that is associated with CultureInfo.InvariantCulture and that is always available.

Methods • Compare - Performs a case-insensitive comparison of two objects of the same type and returns a value indicating whether one

is less than, equal to, or greater than the other.

• Equals(Object) - Determines whether the specified Object is equal to the current Object. (Inherited from Object.)

• Finalize - Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)

• GetHashCode - Serves as a hash function for a particular type. (Inherited from Object.)

• GetType - Gets the Type of the current instance. (Inherited from Object.)

• MemberwiseClone - Creates a shallow copy of the current Object. (Inherited from Object.)

• ToString - Returns a string that represents the current object. (Inherited from Object.)

Page 20: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

CaseInsensitiveComparer

Here is an example:

using System;

using System.Collections;

class MainProgram {

public static void Main() {

CaseInsensitiveComparer cicTEXT = new CaseInsensitiveComparer();

String sText1 = "Are you my mommy?";

String sText2 = "Are You my mommy?";

Int32 iCompareResults = cicTEXT.Compare(sText1,sText2);

Console.WriteLine(iCompareResults); //Results: 0

}

}

Page 21: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Classes

CollectionBase, ReadOnlyCollectionBase, DictionaryBase

The System.Collections Namespace

Page 22: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

CollectionBase, ReadOnlyCollectionBase, DictionaryBase

The CollectionBase class provides the abstract base class for a strongly typed collection. The ReadOnlyCollectionBase class provides the abstract base class for a strongly typed non-generic read-only collection. The DictionaryBase class

provides the abstract base class for a strongly typed collection of key/value pairs.

On Microsoft's website, there is a note to implementers: This base class is provided to make it easier for implementers to create a strongly typed custom collection. Implementers are encouraged to extend this base class instead of creating their own.

Please see the example at: http://msdn.microsoft.com/en-us/library/system.collections.collectionbase.aspx.

Page 23: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Classes

Comparer

The System.Collections Namespace

Page 24: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Comparer

The Comparer class compares two objects for equivalence, where string

comparisons are case-sensitive. According to Microsoft's website: This class is the default implementation of the IComparer interface. The CaseInsensitiveComparer class is the implementation of the IComparer interface that performs case-insensitive string comparisons. Comparison procedures use the Thread.CurrentCulture of the current thread unless otherwise specified. String comparisons might have different results depending on the culture.

Constructors • Comparer - Initializes a new instance of the Comparer class using the specified System.Globalization.CultureInfo.

Fields • Default - Represents an instance of Comparer that is associated with the Thread.CurrentCulture of the current thread. This

field is read-only.

• DefaultInvariant - Represents an instance of Comparer that is associated with CultureInfo.InvariantCulture. This field is read-only.

Methods • Compare - Performs a case-sensitive comparison of two objects of the same type and returns a value indicating whether one

is less than, equal to, or greater than the other.

• Equals(Object) - Determines whether the specified Object is equal to the current Object. (Inherited from Object.)

• Finalize - Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)

• GetHashCode - Serves as a hash function for a particular type. (Inherited from Object.)

• GetObjectData - Populates a SerializationInfo object with the data required for serialization.

• GetType - Gets the Type of the current instance. (Inherited from Object.)

• MemberwiseClone - Creates a shallow copy of the current Object. (Inherited from Object.)

• ToString - Returns a string that represents the current object. (Inherited from Object.)

Page 25: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Comparer

An example is below. Note that we are obtaining the current culture information from the current thread by using the Thread.CurrentThread.CurrentCulture property in the System.Threading namespace.

using System;

using System.Collections;

using System.Threading;

class MainProgram {

public static void Main() {

Comparer cTEXT = new Comparer(Thread.CurrentThread.CurrentCulture);

String sText1 = "Are you my mommy?";

String sText2 = "Are You my mommy?";

Int32 iCompareResults = cTEXT.Compare(sText1,sText2);

Console.WriteLine(iCompareResults); //Results: -1 indicating that sText1 is less than sText2.

}

}

Page 26: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Classes

Hashtable

The System.Collections Namespace

Page 27: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Hashtable

The Hashtable class represents a collection of key/value pairs that are organized

based on the hash code of the key. According to Microsoft's website: Each element is a key/value pair stored in a DictionaryEntry object. A key cannot be null, but a value can be.

The objects used as keys by a Hashtable are required to override the Object.GetHashCode method (or the IHashCodeProvider interface) and the Object.Equals method (or the IComparer interface). The implementation of both methods and interfaces must handle case sensitivity the same way; otherwise, the Hashtable might behave incorrectly. For example, when creating a Hashtable, you must use the CaseInsensitiveHashCodeProvider class (or any case-insensitive IHashCodeProvider implementation) with the CaseInsensitiveComparer class (or any case-insensitive IComparer implementation).

Furthermore, these methods must produce the same results when called with the same parameters while the key exists in the Hashtable. An alternative is to use a Hashtable constructor with an IEqualityComparer parameter. If key equality were simply reference equality, the inherited implementation of Object.GetHashCode and Object.Equals would suffice.

Key objects must be immutable as long as they are used as keys in the Hashtable.

Page 28: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Hashtable

When an element is added to the Hashtable, the element is placed into a bucket based on the hash code of the key. Subsequent lookups of the key use the hash code of the key to search in only one particular bucket, thus substantially reducing the number of key comparisons required to find an element.

The load factor of a Hashtable determines the maximum ratio of elements to buckets. Smaller load factors cause faster average lookup times at the cost of increased memory consumption. The default load factor of 1.0 generally provides the best balance between speed and size. A different load factor can also be specified when the Hashtable is created.

As elements are added to a Hashtable, the actual load factor of the Hashtable increases. When the actual load factor reaches the specified load factor, the number of buckets in the Hashtable is automatically increased to the smallest prime number that is larger than twice the current number of Hashtable buckets.

Each key object in the Hashtable must provide its own hash function, which can be accessed by calling GetHash. However, any object implementing IHashCodeProvider can be passed to a Hashtable constructor, and that hash function is used for all objects in the table.

The capacity of a Hashtable is the number of elements the Hashtable can hold. As elements are added to a Hashtable, the capacity is automatically increased as required through reallocation.

Page 29: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Hashtable

The foreach statement of the C# language (For Each in Visual Basic) requires the type of each element in the collection. Since each element of the Hashtable is a key/value pair, the element type is not the type of the key or the type of the value. Instead, the element type is DictionaryEntry.

Constructors • Hashtable() Initializes a new, empty instance of the Hashtable class using the default initial capacity, load factor, hash code

provider, and comparer. There are 16 overloads to this constructor!

Properties • Count - Gets the number of key/value pairs contained in the Hashtable.

• EqualityComparer - Gets the IEqualityComparer to use for the Hashtable.

• IsFixedSize - Gets a value indicating whether the Hashtable has a fixed size.

• IsReadOnly - Gets a value indicating whether the Hashtable is read-only.

• IsSynchronized - Gets a value indicating whether access to the Hashtable is synchronized (thread safe).

• Item - Gets or sets the value associated with the specified key.

• Keys - Gets an ICollection containing the keys in the Hashtable.

• SyncRoot - Gets an object that can be used to synchronize access to the Hashtable.

• Values - Gets an ICollection containing the values in the Hashtable.

Methods • Add - Adds an element with the specified key and value into the Hashtable.

• Clear - Removes all elements from the Hashtable.

• Clone - Creates a shallow copy of the Hashtable.

• Contains - Determines whether the Hashtable contains a specific key.

• ContainsKey - Determines whether the Hashtable contains a specific key.

• ContainsValue - Determines whether the Hashtable contains a specific value.

• CopyTo - Copies the Hashtable elements to a one-dimensional Array instance at the specified index.

• Equals(Object) - Determines whether the specified Object is equal to the current Object. (Inherited from Object.)

Page 30: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Hashtable

Methods (continued) • Finalize - Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage

collection. (Inherited from Object.)

• GetEnumerator - Returns an IDictionaryEnumerator that iterates through the Hashtable.

• GetHash - Returns the hash code for the specified key.

• GetHashCode - Serves as a hash function for a particular type. (Inherited from Object.)

• GetObjectData - Implements the ISerializable interface and returns the data needed to serialize the Hashtable.

• GetType - Gets the Type of the current instance. (Inherited from Object.)

• KeyEquals - Compares a specific Object with a specific key in the Hashtable.

• MemberwiseClone - Creates a shallow copy of the current Object. (Inherited from Object.)

• OnDeserialization - Implements the ISerializable interface and raises the deserialization event when the deserialization is complete.

• Remove - Removes the element with the specified key from the Hashtable.

• Synchronized - Returns a synchronized (thread-safe) wrapper for the Hashtable.

• ToString - Returns a string that represents the current object. (Inherited from Object.)

Here is a simple example:

class MainProgram {

public static void Main() {

Hashtable hBookISBN = new Hashtable();

hBookISBN.Add("Go-F-Sleep-Adam-Mansbach","1617750255");

hBookISBN.Add("Heaven-Real-Little-Astounding-Story","0849946158");

hBookISBN.Add("Prescription-Excellence-Leadership-Creating-Experience","0071773541");

hBookISBN.Add("Garden-Beasts-Terror-American-Hitlers","0307408841");

hBookISBN.Add("George-Martins-Thrones-4-Book-Boxed","0345529057");

foreach(DictionaryEntry deITEM in hBookISBN) {

Console.WriteLine("Title={0}/ISBN #={1}",deITEM.Key,deITEM.Value);

}

}

}

Page 31: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Hashtable

Notice that, as per Microsoft's instructions, we use the DictionaryEntry structure (see the Structures section in this presentation) to perform a foreach

loop.

Note that if you attempt to insert an existing key, you will be given a System.ArgumentException exception and a fist will come out of your screen and punch you in the mouth. You probably want to avoid that.

Page 32: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Classes

Queue

The System.Collections Namespace

Page 33: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Queue

The Queue class represents a first-in, first-out (FIFO) collection of objects. According to Microsoft's website: Queues are useful for storing messages in the order they were received for sequential processing. This class implements a queue as a circular array. Objects stored in a Queue are inserted at one end and removed from the other. The capacity of a Queue is the number of elements the Queue can hold. As elements are added to a Queue, the capacity is automatically increased as required through reallocation. The capacity can be decreased by calling TrimToSize. The growth factor is the number by which the current capacity is multiplied when a greater capacity is required. The growth factor is determined when the Queue is constructed. The default growth factor is 2.0. The capacity of the Queue will always increase by at least a minimum of four, regardless of the growth factor. For example, a Queue with a growth factor of 1.0 will always increase in capacity by four when a greater capacity is required. Queue accepts null as a valid value and allows duplicate elements. For the generic version of this collection, see System.Collections.Generic.Queue<T>.

Constructors • Queue() - Initializes a new instance of the Queue class that is empty, has the default initial capacity, and uses the default

growth factor.

• Queue(ICollection) - Initializes a new instance of the Queue class that contains elements copied from the specified collection, has the same initial capacity as the number of elements copied, and uses the default growth factor.

• Queue(Int32) - Initializes a new instance of the Queue class that is empty, has the specified initial capacity, and uses the default growth factor.

• Queue(Int32, Single) - Initializes a new instance of the Queue class that is empty, has the specified initial capacity, and uses the specified growth factor.

Page 34: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Queue

Properties • Count - Gets the number of elements contained in the Queue.

• IsSynchronized - Gets a value indicating whether access to the Queue is synchronized (thread safe).

• SyncRoot - Gets an object that can be used to synchronize access to the Queue.

Methods • Clear - Removes all objects from the Queue.

• Clone - Creates a shallow copy of the Queue.

• Contains - Determines whether an element is in the Queue.

• CopyTo - Copies the Queue elements to an existing one-dimensional Array, starting at the specified array index.

• Dequeue - Removes and returns the object at the beginning of the Queue.

• Enqueue - Adds an object to the end of the Queue.

• Equals(Object) - Determines whether the specified Object is equal to the current Object. (Inherited from Object.)

• Finalize - Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)

• GetEnumerator - Returns an enumerator that iterates through the Queue.

• GetHashCode - Serves as a hash function for a particular type. (Inherited from Object.)

• GetType - Gets the Type of the current instance. (Inherited from Object.)

• MemberwiseClone - Creates a shallow copy of the current Object. (Inherited from Object.)

• Peek - Returns the object at the beginning of the Queue without removing it.

• Synchronized - Returns a Queue wrapper that is synchronized (thread safe).

• ToArray - Copies the Queue elements to a new array.

• ToString - Returns a string that represents the current object. (Inherited from Object.)

• TrimToSize - Sets the capacity to the actual number of elements in the Queue.

Below is an example using a Queue.

Page 35: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Queue

using System;

using System.Collections;

class MainProgram {

public static void Main() {

Queue qBookISBN = new Queue();

qBookISBN.Enqueue("1617750255");

qBookISBN.Enqueue("0849946158");

qBookISBN.Enqueue("0071773541");

qBookISBN.Enqueue("0307408841");

qBookISBN.Enqueue("0345529057");

//Does not change the Queue!!

foreach(Object oITEM in qBookISBN) {

Console.WriteLine( (String) oITEM );

}

Console.WriteLine("Number of Elements in the queue={0}",qBookISBN.Count);

//Changes the Queue by deleting elements!!

Int32 iCnt = qBookISBN.Count;

for(Int32 indx=0;indx<iCnt;indx++) {

Console.WriteLine( qBookISBN.Dequeue() );

}

}

}

Take note at the code above where I use the Dequeue() method. Note that I created the variable iCnt to hold the initial count of elements in the queue. If you specify qBookISBN.Count instead of iCnt, then your loop will end

prematurely.

Page 36: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Classes

SortedList

The System.Collections Namespace

Page 37: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

SortedList

The SortedList class represents a collection of key/value pairs that are sorted

by the keys and are accessible by key and by index. According to Microsoft's website: For the generic version of this collection, see System.Collections.Generic.SortedList<TKey, TValue>.

A SortedList element can be accessed by its key, like an element in any IDictionary implementation, or by its index, like an element in any IList implementation.

A SortedList object internally maintains two arrays to store the elements of the list; that is, one array for the keys and another array for the associated values. Each element is a key/value pair that can be accessed as a DictionaryEntry object. A key cannot be null, but a value can be.

The capacity of a SortedList object is the number of elements the SortedList can hold. As elements are added to a SortedList, the capacity is automatically increased as required through reallocation. The capacity can be decreased by calling TrimToSize or by setting the Capacity property explicitly.

The elements of a SortedList object are sorted by the keys either according to a specific IComparer implementation specified when the SortedList is created or according to the IComparable implementation provided by the keys themselves. In either case, a SortedList does not allow duplicate keys.

The index sequence is based on the sort sequence. When an element is added, it is inserted into SortedList in the correct sort order, and the indexing adjusts accordingly.

Page 38: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

SortedList

When an element is removed, the indexing also adjusts accordingly. Therefore, the index of a specific key/value pair might change as elements are added or removed from the SortedList object.

Operations on a SortedList object tend to be slower than operations on a Hashtable object because of the sorting. However, the SortedList offers more flexibility by allowing access to the values either through the associated keys or through the indexes.

Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based.

The foreach statement of the C# language (for each in Visual Basic) requires the type of each element in the collection. Since each element of the SortedList object is a key/value pair, the element type is not the type of the key or the type of the value. Rather, the element type is DictionaryEntry.

Constructors • SortedList() - Initializes a new instance of the SortedList class that is empty, has the default initial capacity, and is sorted

according to the IComparable interface implemented by each key added to the SortedList object.

• SortedList(IComparer) - Initializes a new instance of the SortedList class that is empty, has the default initial capacity, and is sorted according to the specified IComparer interface.

• SortedList(IDictionary) - Initializes a new instance of the SortedList class that contains elements copied from the specified dictionary, has the same initial capacity as the number of elements copied, and is sorted according to the IComparable interface implemented by each key.

• SortedList(Int32) - Initializes a new instance of the SortedList class that is empty, has the specified initial capacity, and is sorted according to the IComparable interface implemented by each key added to the SortedList object.

• SortedList(IComparer, Int32) - Initializes a new instance of the SortedList class that is empty, has the specified initial capacity, and is sorted according to the specified IComparer interface.

• SortedList(IDictionary, IComparer) - Initializes a new instance of the SortedList class that contains elements copied from the specified dictionary, has the same initial capacity as the number of elements copied, and is sorted according to the specified IComparer interface.

Page 39: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

SortedList

Properties • Capacity - Gets or sets the capacity of a SortedList object.

• Count - Gets the number of elements contained in a SortedList object.

• IsFixedSize - Gets a value indicating whether a SortedList object has a fixed size.

• IsReadOnly - Gets a value indicating whether a SortedList object is read-only.

• IsSynchronized - Gets a value indicating whether access to a SortedList object is synchronized (thread safe).

• Item - Gets and sets the value associated with a specific key in a SortedList object.

• Keys - Gets the keys in a SortedList object.

• SyncRoot - Gets an object that can be used to synchronize access to a SortedList object.

• Values - Gets the values in a SortedList object.

Methods • Add - Adds an element with the specified key and value to a SortedList object.

• Clear - Removes all elements from a SortedList object.

• Clone - Creates a shallow copy of a SortedList object.

• Contains - Determines whether a SortedList object contains a specific key.

• ContainsKey - Determines whether a SortedList object contains a specific key.

• ContainsValue - Determines whether a SortedList object contains a specific value.

• CopyTo - Copies SortedList elements to a one-dimensional Array object, starting at the specified index in the array.

• Equals(Object) - Determines whether the specified Object is equal to the current Object. (Inherited from Object.)

• Finalize - Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)

• GetByIndex - Gets the value at the specified index of a SortedList object.

• GetEnumerator - Returns an IDictionaryEnumerator object that iterates through a SortedList object.

• GetHashCode - Serves as a hash function for a particular type. (Inherited from Object.)

• GetKey - Gets the key at the specified index of a SortedList object.

• GetKeyList - Gets the keys in a SortedList object.

• GetType - Gets the Type of the current instance. (Inherited from Object.)

• GetValueList - Gets the values in a SortedList object.

• IndexOfKey - Returns the zero-based index of the specified key in a SortedList object.

• IndexOfValue - Returns the zero-based index of the first occurrence of the specified value in a SortedList object.

• MemberwiseClone - Creates a shallow copy of the current Object. (Inherited from Object.)

.

Page 40: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

SortedList

Methods (continued) • Remove - Removes the element with the specified key from a SortedList object.

• RemoveAt - Removes the element at the specified index of a SortedList object.

• SetByIndex - Replaces the value at a specific index in a SortedList object.

• Synchronized - Returns a synchronized (thread-safe) wrapper for a SortedList object.

• ToString - Returns a string that represents the current object. (Inherited from Object.)

• TrimToSize - Sets the capacity to the actual number of elements in a SortedList object.

A simple example follows:

using System;

using System.Collections;

class MainProgram {

public static void Main() {

SortedList slBookISBN = new SortedList();

slBookISBN.Add("Prescription-Excellence-Leadership-Creating-Experience","0071773541");

slBookISBN.Add("Go-F-Sleep-Adam-Mansbach","1617750255");

slBookISBN.Add("Heaven-Real-Little-Astounding-Story","0849946158");

slBookISBN.Add("Garden-Beasts-Terror-American-Hitlers","0307408841");

slBookISBN.Add("George-Martins-Thrones-4-Book-Boxed","0345529057");

Console.WriteLine("Number of Elements in the SortedList={0}",slBookISBN.Count);

foreach(DictionaryEntry deITEM in slBookISBN) {

Console.WriteLine("SortedList Key={0}/SortedList Value={1}",(String) deITEM.Key, (String) deITEM.Value );

}

}

}

Page 41: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

SortedList

The results are below (note that they are sorted by the keys):

Number of Elements in the SortedList=5

SortedList Key=Garden-Beasts-Terror-American-Hitlers/SortedList Value=0307408841

SortedList Key=George-Martins-Thrones-4-Book-Boxed/SortedList Value=0345529057

SortedList Key=Go-F-Sleep-Adam-Mansbach/SortedList Value=1617750255

SortedList Key=Heaven-Real-Little-Astounding-Story/SortedList Value=0849946158

SortedList Key=Prescription-Excellence-Leadership-Creating-Experience/SortedList Value=0071773541

Page 42: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Classes

Stack

The System.Collections Namespace

Page 43: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Stack

The Stack class represents a simple last-in-first-out (LIFO) non-generic

collection of objects. According to Microsoft's website: For the generic version of this collection, see System.Collections.Generic.Stack<T>. Stack is implemented as a circular buffer. The capacity of a Stack is the number of elements the Stack can hold. As elements are added to a Stack, the capacity is automatically increased as required through reallocation. If Count is less than the capacity of the stack, Push is an O(1) operation. If the capacity needs to be increased to accommodate the new element, Push becomes an O(n) operation, where n is Count. Pop is an O(1) operation. Stack accepts null as a valid value and allows duplicate elements.

Constructors • Stack() - Initializes a new instance of the Stack class that is empty and has the default initial capacity.

• Stack(ICollection) - Initializes a new instance of the Stack class that contains elements copied from the specified collection and has the same initial capacity as the number of elements copied.

• Stack(Int32) - Initializes a new instance of the Stack class that is empty and has the specified initial capacity or the default initial capacity, whichever is greater.

Properties • Count - Gets the number of elements contained in the Stack.

• IsSynchronized - Gets a value indicating whether access to the Stack is synchronized (thread safe).

• SyncRoot - Gets an object that can be used to synchronize access to the Stack.

Methods • Clear - Removes all objects from the Stack.

• Clone - Creates a shallow copy of the Stack.

• Contains - Determines whether an element is in the Stack.

• CopyTo - Copies the Stack to an existing one-dimensional Array, starting at the specified array index.

• Equals(Object) - Determines whether the specified Object is equal to the current Object. (Inherited from Object.)

• Finalize - Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)

Page 44: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Stack

Methods • Finalize - Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage

collection. (Inherited from Object.)

• GetEnumerator - Returns an IEnumerator for the Stack.

• GetHashCode - Serves as a hash function for a particular type. (Inherited from Object.)

• GetType - Gets the Type of the current instance. (Inherited from Object.)

• MemberwiseClone - Creates a shallow copy of the current Object. (Inherited from Object.)

• Peek - Returns the object at the top of the Stack without removing it.

• Pop - Removes and returns the object at the top of the Stack.

• Push - Inserts an object at the top of the Stack.

• Synchronized - Returns a synchronized (thread safe) wrapper for the Stack.

• ToArray - Copies the Stack to a new array.

• ToString - Returns a string that represents the current object. (Inherited from Object.)

An example follows:

using System;

using System.Collections;

class MainProgram {

public static void Main() {

Stack sBookISBN = new Stack();

sBookISBN.Push("0071773541");sBookISBN.Push("1617750255");sBookISBN.Push("0849946158");

sBookISBN.Push("0307408841");sBookISBN.Push("0345529057");

Console.WriteLine("Number of Elements in the Stack={0}",sBookISBN.Count);

foreach(Object oITEM in sBookISBN) {

Console.WriteLine("Stack Item={0}",(String) oITEM);

}

}

}

Page 45: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Stack

The results are below:

Number of Elements in the Stack=5

Stack Item=0345529057

Stack Item=0307408841

Stack Item=0849946158

Stack Item=1617750255

Stack Item=0071773541

Page 46: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Classes

StructuralComparisons

The System.Collections Namespace

Page 47: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

StructuralComparisons

The StructuralComparisons class provides objects for performing a structural

comparison of two collection objects. According to Microsoft's website: The StructuralComparisons class returns the following two predefined comparison objects:

An IComparer implementation that can be passed to a method such as Array.IStructuralComparable.CompareTo(Object, IComparer) or Tuple<T1, T2, T3>.IStructuralComparable.CompareTo(Object, IComparer) to perform a structural comparison of two objects. It is designed to indicate whether the first object precedes, follows, or occurs in the same position as the second object in the sort order.

An IEqualityComparer implementation that can be passed to a method such as Array.IStructuralEquatable.Equals(Object, IEqualityComparer) or Tuple<T1, T2, T3>.IStructuralEquatable.Equals(Object, IEqualityComparer) to perform a comparison for structural equality.

The objects can be used to perform a structural comparison or a structural equality comparison of two collection objects, such as array or tuple objects. In structural comparison, two objects are compared based on their values. Objects can be ordered based on some criteria, and two objects are considered equal when they have equal values, not because they reference the same physical object.

Page 48: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

StructuralComparisons

Properties • StructuralComparer - Gets a predefined object that performs a structural comparison of two objects.

• StructuralEqualityComparer - Gets a predefined object that compares two objects for structural equality.

See Microsoft's website for more on this class.

Page 49: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Structures

The System.Collections Namespace

Page 50: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Structures The structures of the System.Collections namespace are listed below.

Structures • DictionaryEntry - Defines a dictionary key/value pair that can be set or retrieved.

Page 51: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Interfaces

The System.Collections Namespace

Page 52: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Interfaces The interfaces of the System.Collections namespace are listed below.

Interfaces • ICollection - Defines size, enumerators, and synchronization methods for all nongeneric collections. • IComparer - Exposes a method that compares two objects. • IDictionary - Represents a nongeneric collection of key/value pairs. • IDictionaryEnumerator - Enumerates the elements of a nongeneric dictionary. • IEnumerable - Exposes the enumerator, which supports a simple iteration over a non-generic collection. • IEnumerator - Supports a simple iteration over a nongeneric collection. • IEqualityComparer - Defines methods to support the comparison of objects for equality. • IHashCodeProvider - Obsolete. Supplies a hash code for an object, using a custom hash function. • IList - Represents a non-generic collection of objects that can be individually accessed by index. • IStructuralComparable - Supports the structural comparison of collection objects. • IStructuralEquatable - Defines methods to support the comparison of objects for structural equality.

Page 53: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Delegates

The System.Collections Namespace

Page 54: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Delegates There are no delegates in the System.Collections namespace.

Page 55: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Enumerations

The System.Collections Namespace

Page 56: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

Enumerations There are no enumerations in the System.Collections namespace.

Page 57: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

What Next?

In C# Programming IV-#, we look at specific classes within specific namespaces such as the System namespace, the System.Data namespace, etc.

Page 58: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com Copyright ©2011 sheepsqueezers.com

sheepsqueezers.com

References

Introducing Microsoft LINQ, Paolo Pialorsi and Marco Russo, Microsoft Press, ISBN:9780735623910

LINQ Pocket Reference, Joseph Albahari and Ben Albahari, O'Reilly Press, ISBN:9780596519247

Inside C#, Tom Archer and Andrew Whitechapel, Microsoft Press, ISBN:0735616485

C# 4.0 In a Nutshell, O'Reilly Press, Joseph Albahari and Ben Albahari, ISBN:9780596800956

The Object Primer, Scott W. Ambler, Cambridge Press, ISBN:0521540186

CLR via C#, Jeffrey Richter, Microsoft Press, ISBN:9780735621633

Click the book titles below to read more about these books on Amazon.com's website.

Page 59: dotNetLectureSeries CSharpProgrammingIV-2 SystemCollectionssheepsqueezers.com/media/presentations/dotNetLectureSeries... · This presentation as well as other presentations and documents

sheepsqueezers.com

Copyright ©2011 sheepsqueezers.com

Support sheepsqueezers.com If you found this information helpful, please consider

supporting sheepsqueezers.com. There are several

ways to support our site:

Buy me a cup of coffee by clicking on the

following link and donate to my PayPal

account: Buy Me A Cup Of Coffee?.

Visit my Amazon.com Wish list at the following

link and purchase an item:

http://amzn.com/w/3OBK1K4EIWIR6

Please let me know if this document was useful by e-mailing me at [email protected].