COLLECTIONS IN C#




                                     PRESENTATION CONTENT
                                     1.   Concepts Recap
                                     2.   What is a collection?
                                     3.   Types of Collection
                                     4.   Example
                                     5.   References




LAKSHMI MAREDDY
CIS525, BELLEVUE UNIVERSITY, NE
INSTRUCTOR: PROF. STUTTE
1. CONCEPTS RECAP


                       Stacks and Heaps
                       Value and reference
                       Interfaces




2/10/2013   Lakshmi Mareddy CIS525 Bellevue University NE   2
1.1 STACK AND HEAP MEMORY

            TEMPORARY MEMORY


    STACK
    Stores variable types in address' in memory, these variables in programming
    are called local variables and are often stored for short amounts of time while
    a function/method block uses them to compute a task.

     HEAP                                                      Invoke a
     Contains                                                 method in a
     •attributes,                                                heap
     •constructors and
     •methods of a class / object
                                                     Method’s (function’s) variables
                                                     etc. are also stored in stack, but
                                                     not in heap, and destroyed after
                                                     use.


                                        Heap also sits in stack

2/10/2013                Lakshmi Mareddy CIS525 Bellevue University NE                    3
1.2 VALUE & TYPE

 Point myPoint = new Point (0, 0);       // a new value-type variable
 Form myForm = new Form();               // a new reference-type variable
 Test (ref myPoint, ref myForm);         // pass myPoint and myForm by reference

 void Test (ref Point p, ref Form f)
 {
        p.X = 100;                       // This will change myPoint’s position
        f.Text = “Hello, World!”;        // This will change MyForm’s caption
        f = null;                        // This will nuke the myForm variable!
     }




2/10/2013                  Lakshmi Mareddy CIS525 Bellevue University NE           4
1.2 SYSTEM INTERFACES IN C#

 An interface contains only                      interface ISampleInterface {
 the signatures of                                           void SampleMethod();
 methods,                                                    }
 delegates
                                                 class ImplementationClass : ISampleInterface
 or events.                                      {
                                                             // Explicit interface member implementation:
                                                             void ISampleInterface.SampleMethod()
 The implementation of the
                                                             {
 methods is done in the class
                                                                          // Method implementation.
 that implements the interface
                                                             }
Defining an interface offers a new
dimension of flexibility (Anyone                             static void Main()
implementing the interface can
change the way the members are                               {
coded.) while keeping things                                       // Declare an interface instance.
standard so code will still be uniform.                            ISampleInterface obj = new
This, in turn, provides a guarantee
that the code won't break when new                                 ImplementationClass();
methods are coded against the same                                 // Call the member.
interface.                                                         obj.SampleMethod();
                                                             }
                                                 }

  2/10/2013                               Lakshmi Mareddy CIS525 Bellevue University NE                     5
2. WHAT IS A COLLECTION?

Collections are enumerable data                 Closely related data can be
  structures that can be                           handled more efficiently when
  assessed using indexes or                        grouped together into a
  keys.                                            collection.

In plain English, it is a list, with an         Instead of writing separate code
   index, to access the list.                      to handle each individual
                                                   object, you can use the same
In programming terms, we are                       code to process all the
   looking at an array, which has                  elements of a collection.
   an index, and can be accessed
   via the index




2/10/2013               Lakshmi Mareddy CIS525 Bellevue University NE         6
2.1 SYSTEM NAMESPACE


            Basic Interfaces

                iCollection                       iEnumerator




                   iList                         iEnumerable




                                     iDictionary



2/10/2013             Lakshmi Mareddy CIS525 Bellevue University NE   7
2.2 ICOLLECTION

                           System.Collections.Stack
  iCollection              System.Collections.Queue
                           System.Collections.BitArray
                           System.Collections.Specialized.NameValueCollection




2/10/2013       Lakshmi Mareddy CIS525 Bellevue University NE                   8
2.2.1 QUEUE

                                 using System;
The Queue is a data              using System.Collections;
structure that provides
a First-in-First-Out             class Test
collection of items of           {
the System.Object                  static void Main()
type.                              {
                                     Queue queueObject = new Queue();
The Enqueue() method                 queueObject.Enqueue(“Peter");
is responsible for                   queueObject.Enqueue(“Tony");
storing items at the rear            queueObject.Enqueue(“Ralph");
of the Queue                         while (queueObject.Count > 0)

The Dequeue() removes                    Console.WriteLine(queueObject.Dequeue());
them one at a time                       Console.ReadLine();
from the front of the                }
Queue                            }



2/10/2013                   Lakshmi Mareddy CIS525 Bellevue University NE       9
2.3 ILIST


            iList
                     System.Array
                     System.Collections.ArrayList
                     System.Collections.Specialized.StringCollection




                    The iList interface represents
                    collections that only have value.




2/10/2013              Lakshmi Mareddy CIS525 Bellevue University NE   10
2.3.1 ARRAYLIST EXAMPLE


The initial capacity of an            using System;
ArrayList is 16, which is             using System.Collections;
increased once the 17th               class Test
item is stored onto it.               {
                                          static void Main()
                                            {
This repeated memory                              int i = 100;
allocation and copying of                         double d = 20.5;
the items can be quite                            ArrayList arrayList = new ArrayList();
expensive in some                                 arrayList.Capacity = 2;
situations.                                       arrayList.Add(“Peter");
                                                  arrayList.Add(i);
If we explicitly set the                          arrayList.Add(d);
                                                  for (int index = 0; index <arrayList.Count; index++)
initial size, then we can
                                                       Console.WriteLine(arrayList[index]);
improve performance.                              }
                                       }




 2/10/2013                   Lakshmi Mareddy CIS525 Bellevue University NE                      11
2.4 IDICTIONARY


            iDictionary
                              System.Collections.SortedList
                              System.Collections.Hashtable
                              System.Collections.Specialized.HybridDictionary
                              System.Collections.Specialized.ListDictionary




        The iDictionary interface represents
        collections that have name value pairs.

                          A                    Lives at #22, Wisteria Lane

                                                                           Index to another
                    Code 0                     Is color Red
                                                                              collection
                                               Looks at Address Book List
                     Obj X
                                                        (Home)


2/10/2013                      Lakshmi Mareddy CIS525 Bellevue University NE                  12
2.4.1 EXAMPLE

using System;
using System.Collections;                                                Similar to the
using System.Collections.Specialized;                                       StringCollection class.
class Test
{                                                                        StringDictionary class, is a
     static void Main()                                                      Hashtable that has its
     {                                                                       keys as strings only.
         StringDictionary stringList = newStringDictionary();
         stringList.Add("A", “Ralph");
         stringList.Add("B",“China");                                    A Hashtable can contain any
         stringList.Add("C","Jini");                                        object type in its key.
         stringList.Add("D",“Evan");
              foreach (string str in stringList.Values)
            {
                       Console.WriteLine(str);
            }
     }
}


    2/10/2013                   Lakshmi Mareddy CIS525 Bellevue University NE                  13
2.5 IENUMERATOR


            Enumerators only read data in the
            collection; they cannot be used to
            modify the underlying collection.

            Example: C# foreach statement
            Counts through a list, but the statement itself cannot
            modify anything.

            int[] counter = new int[] { 0, 1, 2, 3, 5, 8, 13 };
            foreach (int i in counter) { DO SOMETHING}

                                                                            ACTION AREA
            Moves implicitly through the list                              WHERE CHANGES
                                                                              HAPPEN



2/10/2013                  Lakshmi Mareddy CIS525 Bellevue University NE            14
2.6 IENUMERATOR


        String names[]=new String[2] {”Rodney”,”Stutte”,”Cass”};
        for(IEnumerator e =names.GetEnumerator();
        e.MoveNext();
        Response.Write(e.Current));


                                                              Output:
             CURRENT, MOVENEXT, RESET                         Rodney
                                                               Stutte
                                                                Cass

            Moves explicitly through the list
                   Via e.MoveNext();




2/10/2013                  Lakshmi Mareddy CIS525 Bellevue University NE   15
2.7 IENUMERABLE


     IEnumerable is a great example of an interface.
     IEnumerable defines just one method:GetEnumerator.
     This method returns an Enumerator object for a
     collection and that lets you step through the collection
     with the For ... Each syntax.




2/10/2013                Lakshmi Mareddy CIS525 Bellevue University NE   16
3 WHAT TYPE OF COLLECTION?


                                       Sequential List
                                       Index Access
                                       Key/Value or both
                                       Sortable List
                                       Fast Searches
                                       Only String Type




2/10/2013       Lakshmi Mareddy CIS525 Bellevue University NE   17
SEQUENTIAL LIST

     • Sequential list where the element is typically
       discarded after its value is retrieved
            • Queue / Queue generic class / FIFO behavior.
            • Stack class / Stack generic class / LIFO behavior.
     • The LinkedList generic class allows sequential
       access either from the head to the tail or from the
       tail to the head.




2/10/2013               Lakshmi Mareddy CIS525 Bellevue University NE   18
ACCESS BY INDEX

     • The ArrayList and StringCollection classes and
       the List generic class offer access to their
       elements by the zero-based index of the element.
     • The Hashtable, SortedList, ListDictionary, and
       StringDictionary classes, and the Dictionary
       and SortedDictionary generic classes offer
       access to their elements by the key of the
       element.
     • The NameObjectCollectionBase and
       NameValueCollection classes, and the
       KeyedCollection and SortedList generic classes
       offer access to their elements by either the zero-
       based index or the key of the element.


2/10/2013         Lakshmi Mareddy CIS525 Bellevue University NE   19
ACCESS BY KEY OR VALUE OR BOTH

     • One value: Use any of the collections based on
       the IList interface or the IList generic interface.
     • One key and one value: Use any of the collections
       based on the IDictionary interface or the
       IDictionary generic interface.
     • One value with embedded key: Use the
       KeyedCollection generic class.
     • One key and multiple values: Use the
       NameValueCollection class.




2/10/2013          Lakshmi Mareddy CIS525 Bellevue University NE   20
SORTABLE LIST


     • The Hashtable class sorts its elements by their hash
            codes.
     • The SortedList class and the SortedDictionary
            and SortedList generic classes sort their elements by
            the key, based on implementations of the iComparer
            interface and the iComparer generic interface.
     • ArrayList provides a Sort method that takes an
            IComparer implementation as a parameter. Its
            generic counterpart, the List generic class, provides
            a Sort method that takes an implementation of the
            iComparer generic interface as a parameter.

2/10/2013               Lakshmi Mareddy CIS525 Bellevue University NE   21
FAST SEARCHES


     • ListDictionary is faster than Hashtable for small
            collections (10 items or fewer).

     • The SortedDictionary generic class provides
            faster lookup than the Dictionary generic class.




2/10/2013               Lakshmi Mareddy CIS525 Bellevue University NE   22
COLLECTIONS THAT ACCEPT ONLY STRING


     • StringCollection (based on IList) and
            StringDictionary (based on IDictionary) are in
            the System.Collections.Specialized
            namespace.



            You can use any of the generic collection classes
            in the System.Collections.Generic namespace
            as strongly typed string collections by specifying
            the String class for their generic type arguments.

2/10/2013              Lakshmi Mareddy CIS525 Bellevue University NE   23
4. EXAMPLES


                                   Okay one final example




2/10/2013   Lakshmi Mareddy CIS525 Bellevue University NE   24
ONE FINAL EXAMPLE
              using System;
Output        using System.Collections;

True          class Program
              {
True             static Hashtable GetHashtable()
                 {
1000                // Create and return new Hashtable.
                    Hashtable hashtable = new Hashtable();
                    hashtable.Add("Area", 1000);
                    hashtable.Add("Perimeter", 55);
                    hashtable.Add("Mortgage", 540);
                    return hashtable;
                 }

                  static void Main()
                  {
                     Hashtable hashtable = GetHashtable();

                      // See if the Hashtable contains this key.
                      Console.WriteLine(hashtable.ContainsKey("Perimeter"));

                      // Test the Contains method. It works the same way.
                      Console.WriteLine(hashtable.Contains("Area"));

                      // Get value of Area with indexer.
                      int value = (int)hashtable["Area"];

                      // Write the value of Area.
                      Console.WriteLine(value);
                  }
              }




  2/10/2013                         Lakshmi Mareddy CIS525 Bellevue University NE   25
5. REFERENCES

Kanjilal J, Working with collections in C#, retrieved on Dec15, 2010 from
http://aspalliance.com/854

Allen Sam, C# Hashtable Use, Lookups and Examples, retrieved on Dec15, 2010 from
http://dotnetperls.com/hashtable

MSDN, Creating and Manipulating Collections, retrieved on Dec15, 2010 from
http://msdn.microsoft.com/en-us/library/14ek9axh(v=vs.80).aspx

MSDN, IEnumerable Interface, retrieved on Dec15, 2010 from
http://msdn.microsoft.com/en-us/library/14ek9axh(v=vs.80).aspx

Albahari Joseph, C# Concepts: Value vs Reference Types, retrieved on Dec15, 2010
from http://www.albahari.com/valuevsreftypes.aspx



  2/10/2013                Lakshmi Mareddy CIS525 Bellevue University NE           26

Collections in-csharp

  • 1.
    COLLECTIONS IN C# PRESENTATION CONTENT 1. Concepts Recap 2. What is a collection? 3. Types of Collection 4. Example 5. References LAKSHMI MAREDDY CIS525, BELLEVUE UNIVERSITY, NE INSTRUCTOR: PROF. STUTTE
  • 2.
    1. CONCEPTS RECAP Stacks and Heaps Value and reference Interfaces 2/10/2013 Lakshmi Mareddy CIS525 Bellevue University NE 2
  • 3.
    1.1 STACK ANDHEAP MEMORY TEMPORARY MEMORY STACK Stores variable types in address' in memory, these variables in programming are called local variables and are often stored for short amounts of time while a function/method block uses them to compute a task. HEAP Invoke a Contains method in a •attributes, heap •constructors and •methods of a class / object Method’s (function’s) variables etc. are also stored in stack, but not in heap, and destroyed after use. Heap also sits in stack 2/10/2013 Lakshmi Mareddy CIS525 Bellevue University NE 3
  • 4.
    1.2 VALUE &TYPE Point myPoint = new Point (0, 0); // a new value-type variable Form myForm = new Form(); // a new reference-type variable Test (ref myPoint, ref myForm); // pass myPoint and myForm by reference void Test (ref Point p, ref Form f) { p.X = 100; // This will change myPoint’s position f.Text = “Hello, World!”; // This will change MyForm’s caption f = null; // This will nuke the myForm variable! } 2/10/2013 Lakshmi Mareddy CIS525 Bellevue University NE 4
  • 5.
    1.2 SYSTEM INTERFACESIN C# An interface contains only interface ISampleInterface { the signatures of void SampleMethod(); methods, } delegates class ImplementationClass : ISampleInterface or events. { // Explicit interface member implementation: void ISampleInterface.SampleMethod() The implementation of the { methods is done in the class // Method implementation. that implements the interface } Defining an interface offers a new dimension of flexibility (Anyone static void Main() implementing the interface can change the way the members are { coded.) while keeping things // Declare an interface instance. standard so code will still be uniform. ISampleInterface obj = new This, in turn, provides a guarantee that the code won't break when new ImplementationClass(); methods are coded against the same // Call the member. interface. obj.SampleMethod(); } } 2/10/2013 Lakshmi Mareddy CIS525 Bellevue University NE 5
  • 6.
    2. WHAT ISA COLLECTION? Collections are enumerable data Closely related data can be structures that can be handled more efficiently when assessed using indexes or grouped together into a keys. collection. In plain English, it is a list, with an Instead of writing separate code index, to access the list. to handle each individual object, you can use the same In programming terms, we are code to process all the looking at an array, which has elements of a collection. an index, and can be accessed via the index 2/10/2013 Lakshmi Mareddy CIS525 Bellevue University NE 6
  • 7.
    2.1 SYSTEM NAMESPACE Basic Interfaces iCollection iEnumerator iList iEnumerable iDictionary 2/10/2013 Lakshmi Mareddy CIS525 Bellevue University NE 7
  • 8.
    2.2 ICOLLECTION System.Collections.Stack iCollection System.Collections.Queue System.Collections.BitArray System.Collections.Specialized.NameValueCollection 2/10/2013 Lakshmi Mareddy CIS525 Bellevue University NE 8
  • 9.
    2.2.1 QUEUE using System; The Queue is a data using System.Collections; structure that provides a First-in-First-Out class Test collection of items of { the System.Object static void Main() type. { Queue queueObject = new Queue(); The Enqueue() method queueObject.Enqueue(“Peter"); is responsible for queueObject.Enqueue(“Tony"); storing items at the rear queueObject.Enqueue(“Ralph"); of the Queue while (queueObject.Count > 0) The Dequeue() removes Console.WriteLine(queueObject.Dequeue()); them one at a time Console.ReadLine(); from the front of the } Queue } 2/10/2013 Lakshmi Mareddy CIS525 Bellevue University NE 9
  • 10.
    2.3 ILIST iList System.Array System.Collections.ArrayList System.Collections.Specialized.StringCollection The iList interface represents collections that only have value. 2/10/2013 Lakshmi Mareddy CIS525 Bellevue University NE 10
  • 11.
    2.3.1 ARRAYLIST EXAMPLE Theinitial capacity of an using System; ArrayList is 16, which is using System.Collections; increased once the 17th class Test item is stored onto it. { static void Main() { This repeated memory int i = 100; allocation and copying of double d = 20.5; the items can be quite ArrayList arrayList = new ArrayList(); expensive in some arrayList.Capacity = 2; situations. arrayList.Add(“Peter"); arrayList.Add(i); If we explicitly set the arrayList.Add(d); for (int index = 0; index <arrayList.Count; index++) initial size, then we can Console.WriteLine(arrayList[index]); improve performance. } } 2/10/2013 Lakshmi Mareddy CIS525 Bellevue University NE 11
  • 12.
    2.4 IDICTIONARY iDictionary System.Collections.SortedList System.Collections.Hashtable System.Collections.Specialized.HybridDictionary System.Collections.Specialized.ListDictionary The iDictionary interface represents collections that have name value pairs. A Lives at #22, Wisteria Lane Index to another Code 0 Is color Red collection Looks at Address Book List Obj X (Home) 2/10/2013 Lakshmi Mareddy CIS525 Bellevue University NE 12
  • 13.
    2.4.1 EXAMPLE using System; usingSystem.Collections; Similar to the using System.Collections.Specialized; StringCollection class. class Test { StringDictionary class, is a static void Main() Hashtable that has its { keys as strings only. StringDictionary stringList = newStringDictionary(); stringList.Add("A", “Ralph"); stringList.Add("B",“China"); A Hashtable can contain any stringList.Add("C","Jini"); object type in its key. stringList.Add("D",“Evan"); foreach (string str in stringList.Values) { Console.WriteLine(str); } } } 2/10/2013 Lakshmi Mareddy CIS525 Bellevue University NE 13
  • 14.
    2.5 IENUMERATOR Enumerators only read data in the collection; they cannot be used to modify the underlying collection. Example: C# foreach statement Counts through a list, but the statement itself cannot modify anything. int[] counter = new int[] { 0, 1, 2, 3, 5, 8, 13 }; foreach (int i in counter) { DO SOMETHING} ACTION AREA Moves implicitly through the list WHERE CHANGES HAPPEN 2/10/2013 Lakshmi Mareddy CIS525 Bellevue University NE 14
  • 15.
    2.6 IENUMERATOR String names[]=new String[2] {”Rodney”,”Stutte”,”Cass”}; for(IEnumerator e =names.GetEnumerator(); e.MoveNext(); Response.Write(e.Current)); Output: CURRENT, MOVENEXT, RESET Rodney Stutte Cass Moves explicitly through the list Via e.MoveNext(); 2/10/2013 Lakshmi Mareddy CIS525 Bellevue University NE 15
  • 16.
    2.7 IENUMERABLE IEnumerable is a great example of an interface. IEnumerable defines just one method:GetEnumerator. This method returns an Enumerator object for a collection and that lets you step through the collection with the For ... Each syntax. 2/10/2013 Lakshmi Mareddy CIS525 Bellevue University NE 16
  • 17.
    3 WHAT TYPEOF COLLECTION? Sequential List Index Access Key/Value or both Sortable List Fast Searches Only String Type 2/10/2013 Lakshmi Mareddy CIS525 Bellevue University NE 17
  • 18.
    SEQUENTIAL LIST • Sequential list where the element is typically discarded after its value is retrieved • Queue / Queue generic class / FIFO behavior. • Stack class / Stack generic class / LIFO behavior. • The LinkedList generic class allows sequential access either from the head to the tail or from the tail to the head. 2/10/2013 Lakshmi Mareddy CIS525 Bellevue University NE 18
  • 19.
    ACCESS BY INDEX • The ArrayList and StringCollection classes and the List generic class offer access to their elements by the zero-based index of the element. • The Hashtable, SortedList, ListDictionary, and StringDictionary classes, and the Dictionary and SortedDictionary generic classes offer access to their elements by the key of the element. • The NameObjectCollectionBase and NameValueCollection classes, and the KeyedCollection and SortedList generic classes offer access to their elements by either the zero- based index or the key of the element. 2/10/2013 Lakshmi Mareddy CIS525 Bellevue University NE 19
  • 20.
    ACCESS BY KEYOR VALUE OR BOTH • One value: Use any of the collections based on the IList interface or the IList generic interface. • One key and one value: Use any of the collections based on the IDictionary interface or the IDictionary generic interface. • One value with embedded key: Use the KeyedCollection generic class. • One key and multiple values: Use the NameValueCollection class. 2/10/2013 Lakshmi Mareddy CIS525 Bellevue University NE 20
  • 21.
    SORTABLE LIST • The Hashtable class sorts its elements by their hash codes. • The SortedList class and the SortedDictionary and SortedList generic classes sort their elements by the key, based on implementations of the iComparer interface and the iComparer generic interface. • ArrayList provides a Sort method that takes an IComparer implementation as a parameter. Its generic counterpart, the List generic class, provides a Sort method that takes an implementation of the iComparer generic interface as a parameter. 2/10/2013 Lakshmi Mareddy CIS525 Bellevue University NE 21
  • 22.
    FAST SEARCHES • ListDictionary is faster than Hashtable for small collections (10 items or fewer). • The SortedDictionary generic class provides faster lookup than the Dictionary generic class. 2/10/2013 Lakshmi Mareddy CIS525 Bellevue University NE 22
  • 23.
    COLLECTIONS THAT ACCEPTONLY STRING • StringCollection (based on IList) and StringDictionary (based on IDictionary) are in the System.Collections.Specialized namespace. You can use any of the generic collection classes in the System.Collections.Generic namespace as strongly typed string collections by specifying the String class for their generic type arguments. 2/10/2013 Lakshmi Mareddy CIS525 Bellevue University NE 23
  • 24.
    4. EXAMPLES Okay one final example 2/10/2013 Lakshmi Mareddy CIS525 Bellevue University NE 24
  • 25.
    ONE FINAL EXAMPLE using System; Output using System.Collections; True class Program { True static Hashtable GetHashtable() { 1000 // Create and return new Hashtable. Hashtable hashtable = new Hashtable(); hashtable.Add("Area", 1000); hashtable.Add("Perimeter", 55); hashtable.Add("Mortgage", 540); return hashtable; } static void Main() { Hashtable hashtable = GetHashtable(); // See if the Hashtable contains this key. Console.WriteLine(hashtable.ContainsKey("Perimeter")); // Test the Contains method. It works the same way. Console.WriteLine(hashtable.Contains("Area")); // Get value of Area with indexer. int value = (int)hashtable["Area"]; // Write the value of Area. Console.WriteLine(value); } } 2/10/2013 Lakshmi Mareddy CIS525 Bellevue University NE 25
  • 26.
    5. REFERENCES Kanjilal J,Working with collections in C#, retrieved on Dec15, 2010 from http://aspalliance.com/854 Allen Sam, C# Hashtable Use, Lookups and Examples, retrieved on Dec15, 2010 from http://dotnetperls.com/hashtable MSDN, Creating and Manipulating Collections, retrieved on Dec15, 2010 from http://msdn.microsoft.com/en-us/library/14ek9axh(v=vs.80).aspx MSDN, IEnumerable Interface, retrieved on Dec15, 2010 from http://msdn.microsoft.com/en-us/library/14ek9axh(v=vs.80).aspx Albahari Joseph, C# Concepts: Value vs Reference Types, retrieved on Dec15, 2010 from http://www.albahari.com/valuevsreftypes.aspx 2/10/2013 Lakshmi Mareddy CIS525 Bellevue University NE 26