collection classes in c#blk/cs3490/ch09/collections.pdfcollection classes in c# ... zero if x is...

Post on 22-May-2020

5 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Collection Classes in C#• There are five types of collection classes

– non-generic, we will not cover these since they exist for backward compatibility

– generic, these are very similar to Java, we will introduce through a table of operations

– bit-based, a quick look with focus on operations

– specialized, just to let you know they are here

– concurrent, will cover later in the course

• We also look at iterators and enumerators

• This material was borrowed from C# 4.0: The Complete Reference by Herbert Schildt

The Generic Collections

• Note: in C# style programming it is customary to put I before the names of interfaces

ICollection<T> Methods

IList<T> Methods

IDictionary<TKey,

TValue> Methods

andProperties

ISet <T>

IEnumerable<T> and IEnumerator<T>• IEnumerable<T>

– IEnumerable<T> declares the GetEnumerator( ) method

– It returns an enumerator of type T for the collection

• IEnumerator<T> has two methods

– MoveNext( ) and Reset( )

– It also declares T Current { get; } that returns a T reference to the next object

– Notice how C# allows getter and setter methods to be added by using { get; set; } as needed

IComparer<T> and IEqualityComparer<T>

• IComparer<T>

– Must implement the method int Compare(T x, T y)

– This method compares x with y and returns greater than zero if x is greater than y, zero if the two objects are the same, and less than zero if x is less that y.

• IEqualityComparer<T>

– Two methods: bool Equals(T x, T y) andint GetHashCode(T obj)

– Equals( ) must return true if x and y are equal.

– GetHashCode( ) must return the hash code for obj.

– If two objects compare as equal, then their hash codes must also be the same.

The Core Generic Classes Themselves

Selected Methods for List - 1

Selected Methods for List - 2

SelectedMethods

forLinked List

Methods and Properties for Dictionary

Methods and Properties for SortedDictionary

Methods and Properties for SortedList

Stack and Queue Methods

Homework Exercises• Consider your project and try to propose a use for

– A generic List or SortedList

– A generic Dictionary or SortedDictionary

to hold data you will be processing

• If you cannot come up with two examples of these structures can you use a set or a stack or a queue?

• Show the declaration of your choices specifying the types to be used

• Describe how the collections will be used in the overall project application

Methods in BitArray

• BitArrays can be indexed. Each index specifies an individual bit, with an index of zero indicating the low-order bit.

The Specialized Collections

foreach loops in C#• A simple examplepublic IEnumerator GetEnumerator() {

foreach(char ch in chrs)

yield return ch;

}

• The yield return statement returns the next object in the collection

Using IComparable<T>• You need to implement the CompareTo method

int CompareTo(T other)

– To sort in ascending order, return zero if the objects are equal, a positive value if the invoking object is greater than other, and a negative value if the invoking object is less than other.

– To sort in descending order, reverse the outcome of the comparison.

• Example let public Inventory(string n, double c, int h) { name = n; cost = c; onhand = h; }

public int CompareTo(Inventory other) { return string.Compare(name, other.name, StringComparison.Ordinal);

} // compares based on string name

Using a Generic List - 1class Inventory {

string name;

double cost;

int onhand;

public Inventory(string n, double c, int h) {

name = n;

cost = c;

onhand = h;

}

public override string ToString() {

return String.Format("{0, -10} Cost: {1, 6: C} On hand: {2}",

name, cost, onhand);

}

}

class TypeSafeInventoryList {

static void Main() {

List<Inventory> inv = new List<Inventory>();

// Add elements to the list

inv.Add(new Inventory( "Pliers", 5.95, 3) );

Using a Generic List - 2inv.Add(new Inventory( "Wrenches" , 8.29, 2) );

inv.Add(new Inventory( "Hammers", 3.50, 4) );

inv.Add(new Inventory( "Drills", 19.88, 8) );

Console.WriteLine("Inventory list: ");

foreach(Inventory i in inv) {

Console.WriteLine(" " + i); // uses custom toString

}

}

}

Inventory list:

Pliers Cost: $5.95 On hand: 3

Wrenches Cost: $8.29 On hand: 2

Hammers Cost: $3.50 On hand: 4

Drills Cost: $19.88 On hand: 8

Using IComparable - 1class Inventory : IComparable<Inventory> {

string name;

double cost;

int onhand;

public Inventory(string n, double c, int h) {

name = n;

cost = c;

onhand = h;

}

public override string ToString() {

return String.Format("{0, -10} Cost: {1, 6: C} On hand: {2}",

name, cost, onhand);

}

// Implement the IComparable<T> interface.

public int CompareTo(Inventory other) {

return string.Compare( name, other.name, StringComparison.Ordinal);

}

}

Using IComparable - 2class GenericIComparableDemo {

static void Main() {

List<Inventory> inv = new List<Inventory>();

// Add elements to the list.

inv.Add(new Inventory( "Pliers", 5.95, 3) );

inv.Add(new Inventory( "Wrenches" , 8.29, 2) );

inv.Add(new Inventory( "Hammers", 3.50, 4) );

inv.Add(new Inventory( "Drills", 19.88, 8) );

Console.WriteLine("Inventory list before sorting: ");

foreach(Inventory i in inv) {

Console.WriteLine(" " + i);

}

Console.WriteLine();

// Sort the list.

inv.Sort();

Console.WriteLine("Inventory list after sorting: ");

foreach(Inventory i in inv) {

Console.WriteLine(" " + i);

}

}

}

Using IComparable - 3Here is the output. Notice after the call to Sort( ), the

inventory is sorted by name.

Inventory list before sorting:

Pliers Cost: $5.95 On hand: 3

Wrenches Cost: $8.29 On hand: 2

Hammers Cost: $3.50 On hand: 4

Drills Cost: $19.88 On hand: 8

Inventory list after sorting:

Drills Cost: $19.88 On hand: 8

Hammers Cost: $3.50 On hand: 4

Pliers Cost: $5.95 On hand: 3

Wrenches Cost: $8.29 On hand: 2

Using IDictionaryEnumerator - 1class IDicEnumDemo {

static void Main() {

// Create a hash table.

Hashtable ht = new Hashtable();

// Add elements to the table.

ht.Add("Tom" , "555–3456");

ht.Add("Mary", "555–9876");

ht.Add("Todd", "555–3452");

ht.Add("Ken" , "555–7756");

// Demonstrate enumerator.

IDictionaryEnumerator etr = ht.GetEnumerator();

Console.WriteLine("Display info using Entry. ");

Using IDictionaryEnumerator - 2while(etr.MoveNext() )

Console.WriteLine(etr.Entry.Key + ": " +

etr.Entry.Value);

Console.WriteLine();

Console.WriteLine("Display info using Key and Value directly. ");

etr.Reset();

while(etr.MoveNext() )

Console.WriteLine(etr.Key + ": " + etr.Value);

}

}

Display info using Entry.

Ken: 555–7756

Mary: 555–9876

Tom: 555–3456

Todd: 555–3452

Display info using Key and Value directly.

Ken: 555–7756

Mary: 555–9876

Tom: 555–3456

Todd: 555–3452

Generic Iterators - 1class MyClass<T> {

T[] array;

public MyClass(T[] a) {

array = a;

}

// This iterator returns the characters

// in the chrs array.

public IEnumerator<T> GetEnumerator() {

foreach(T obj in array)

yield return obj;

}

}

class GenericItrDemo {

static void Main() {

int[] nums = { 4, 3, 6, 4, 7, 9 };

MyClass<int> mc = new MyClass<int>(nums);

foreach(int x in mc)

Console.Write(x + " ");

Console.WriteLine();

Generic Iterators - 2

bool[] bVals = { true, true, false, true };

MyClass<bool> mc2 = new MyClass<bool>(bVals);

foreach(bool b in mc2)

Console.Write(b + " ");

Console.WriteLine();

}

}

4 3 6 4 7 9

True True False True

The Concurrent Collections

A Blocking Collection - 1class BlockingDemo {

static BlockingCollection<char> bc;

// Produce the characters A to Z.

static void Producer() {

for(char ch = ' A'; ch <= ' Z'; ch++) {

bc.Add(ch);

Console.WriteLine("Producing " + ch);

}

}

// Consume 26 characters.

static void Consumer() {

for(int i=0; i < 26; i++)

Console.WriteLine("Consuming " + bc.Take( ) );

}

static void Main() {

// Use a blocking collection that has a bound of 4.

bc = new BlockingCollection<char>(4);

// Create the producer and consumer tasks.

A Blocking Collection - 2Task Prod = new Task(Producer);

Task Con = new Task(Consumer);

// Start the tasks.

Con.Start();

Prod.Start( );

// Wait for both to finish.

try {

Task.WaitAll(Con, Prod);

} catch(AggregateException exc) {

Console.WriteLine(exc);

} finally {

Con.Dispose();

Prod.Dispose();

bc.Dispose();

}

}

}

top related