SlideShare ist ein Scribd-Unternehmen logo
1 von 26
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

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Java collection
Java collectionJava collection
Java collection
 
Generics C#
Generics C#Generics C#
Generics C#
 
Inheritance C#
Inheritance C#Inheritance C#
Inheritance C#
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in Java
 
C# Arrays
C# ArraysC# Arrays
C# Arrays
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
4. Classes and Methods
4. Classes and Methods4. Classes and Methods
4. Classes and Methods
 
JAVA Collections frame work ppt
 JAVA Collections frame work ppt JAVA Collections frame work ppt
JAVA Collections frame work ppt
 
C# in depth
C# in depthC# in depth
C# in depth
 
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Oops ppt
Oops pptOops ppt
Oops ppt
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
C# Inheritance
C# InheritanceC# Inheritance
C# Inheritance
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and Interface
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 

Andere mochten auch

Bn1001 demo ppt advance dot net
Bn1001 demo ppt advance dot netBn1001 demo ppt advance dot net
Bn1001 demo ppt advance dot netconline training
 
Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and JavaSasha Goldshtein
 
9 subprograms
9 subprograms9 subprograms
9 subprogramsjigeno
 
Auteursrecht in academische omgeving: DPO Professionaliseringsbijeenkomst, 23...
Auteursrecht in academische omgeving: DPO Professionaliseringsbijeenkomst, 23...Auteursrecht in academische omgeving: DPO Professionaliseringsbijeenkomst, 23...
Auteursrecht in academische omgeving: DPO Professionaliseringsbijeenkomst, 23...Leon Osinski
 
A basic course on Research data management: part 1 - part 4
A basic course on Research data management: part 1 - part 4A basic course on Research data management: part 1 - part 4
A basic course on Research data management: part 1 - part 4Leon Osinski
 
3963066 pl-sql-notes-only
3963066 pl-sql-notes-only3963066 pl-sql-notes-only
3963066 pl-sql-notes-onlyAshwin Kumar
 
Oracle database 12c sql worshop 1 activity guide
Oracle database 12c sql worshop 1 activity guideOracle database 12c sql worshop 1 activity guide
Oracle database 12c sql worshop 1 activity guideOtto Paiz
 
16 logical programming
16 logical programming16 logical programming
16 logical programmingjigeno
 
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutionsAshwin Kumar
 
C# Tutorial
C# Tutorial C# Tutorial
C# Tutorial Jm Ramos
 
Software engineering lecture notes
Software engineering lecture notesSoftware engineering lecture notes
Software engineering lecture notesSiva Ayyakutti
 
Free PMP notes,Free PMP Study Material,Free PMP Chapter wise notes,PMP Exam N...
Free PMP notes,Free PMP Study Material,Free PMP Chapter wise notes,PMP Exam N...Free PMP notes,Free PMP Study Material,Free PMP Chapter wise notes,PMP Exam N...
Free PMP notes,Free PMP Study Material,Free PMP Chapter wise notes,PMP Exam N...TURKI , PMP
 

Andere mochten auch (20)

Generics collections
Generics collectionsGenerics collections
Generics collections
 
Collection
CollectionCollection
Collection
 
Bn1001 demo ppt advance dot net
Bn1001 demo ppt advance dot netBn1001 demo ppt advance dot net
Bn1001 demo ppt advance dot net
 
Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and Java
 
Oops
OopsOops
Oops
 
9 subprograms
9 subprograms9 subprograms
9 subprograms
 
Auteursrecht in academische omgeving: DPO Professionaliseringsbijeenkomst, 23...
Auteursrecht in academische omgeving: DPO Professionaliseringsbijeenkomst, 23...Auteursrecht in academische omgeving: DPO Professionaliseringsbijeenkomst, 23...
Auteursrecht in academische omgeving: DPO Professionaliseringsbijeenkomst, 23...
 
Raspuns MS Subprogram FIV 2016
Raspuns MS Subprogram FIV 2016Raspuns MS Subprogram FIV 2016
Raspuns MS Subprogram FIV 2016
 
A basic course on Research data management: part 1 - part 4
A basic course on Research data management: part 1 - part 4A basic course on Research data management: part 1 - part 4
A basic course on Research data management: part 1 - part 4
 
3963066 pl-sql-notes-only
3963066 pl-sql-notes-only3963066 pl-sql-notes-only
3963066 pl-sql-notes-only
 
16 exception handling - i
16 exception handling - i16 exception handling - i
16 exception handling - i
 
Oracle database 12c sql worshop 1 activity guide
Oracle database 12c sql worshop 1 activity guideOracle database 12c sql worshop 1 activity guide
Oracle database 12c sql worshop 1 activity guide
 
16 logical programming
16 logical programming16 logical programming
16 logical programming
 
Delegates and events
Delegates and events   Delegates and events
Delegates and events
 
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions
 
Csci360 08-subprograms
Csci360 08-subprogramsCsci360 08-subprograms
Csci360 08-subprograms
 
Programming in c#
Programming in c#Programming in c#
Programming in c#
 
C# Tutorial
C# Tutorial C# Tutorial
C# Tutorial
 
Software engineering lecture notes
Software engineering lecture notesSoftware engineering lecture notes
Software engineering lecture notes
 
Free PMP notes,Free PMP Study Material,Free PMP Chapter wise notes,PMP Exam N...
Free PMP notes,Free PMP Study Material,Free PMP Chapter wise notes,PMP Exam N...Free PMP notes,Free PMP Study Material,Free PMP Chapter wise notes,PMP Exam N...
Free PMP notes,Free PMP Study Material,Free PMP Chapter wise notes,PMP Exam N...
 

Ähnlich wie Collections in-csharp

iOS development introduction
iOS development introduction iOS development introduction
iOS development introduction paramisoft
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .NetGreg Sohl
 
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMU
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMUAutomated Refactoring of Legacy Java Software to Default Methods Talk at GMU
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMURaffi Khatchadourian
 
Object oriented basics
Object oriented basicsObject oriented basics
Object oriented basicsvamshimahi
 
Unit3 packages &amp; interfaces
Unit3 packages &amp; interfacesUnit3 packages &amp; interfaces
Unit3 packages &amp; interfacesKalai Selvi
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programmingNeelesh Shukla
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfacesmadhavi patil
 
Data Structure Interview Questions & Answers
Data Structure Interview Questions & AnswersData Structure Interview Questions & Answers
Data Structure Interview Questions & AnswersSatyam Jaiswal
 
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptxINDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptxIndu65
 
Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013Steven Smith
 
Fundamentals of oops in .Net
Fundamentals of oops in .NetFundamentals of oops in .Net
Fundamentals of oops in .NetHarman Bajwa
 
12 object oriented programming
12 object oriented programming12 object oriented programming
12 object oriented programmingjigeno
 

Ähnlich wie Collections in-csharp (20)

C#
C#C#
C#
 
iOS development introduction
iOS development introduction iOS development introduction
iOS development introduction
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .Net
 
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMU
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMUAutomated Refactoring of Legacy Java Software to Default Methods Talk at GMU
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMU
 
Object oriented basics
Object oriented basicsObject oriented basics
Object oriented basics
 
Unit3 packages &amp; interfaces
Unit3 packages &amp; interfacesUnit3 packages &amp; interfaces
Unit3 packages &amp; interfaces
 
Core_Java_Interview.pdf
Core_Java_Interview.pdfCore_Java_Interview.pdf
Core_Java_Interview.pdf
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programming
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
C# interview
C# interviewC# interview
C# interview
 
C# interview
C# interviewC# interview
C# interview
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Data Structure Interview Questions & Answers
Data Structure Interview Questions & AnswersData Structure Interview Questions & Answers
Data Structure Interview Questions & Answers
 
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptxINDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
 
Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013
 
Fundamentals of oops in .Net
Fundamentals of oops in .NetFundamentals of oops in .Net
Fundamentals of oops in .Net
 
12 object oriented programming
12 object oriented programming12 object oriented programming
12 object oriented programming
 
201005 accelerometer and core Location
201005 accelerometer and core Location201005 accelerometer and core Location
201005 accelerometer and core Location
 
python.pptx
python.pptxpython.pptx
python.pptx
 

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 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
  • 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 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
  • 6. 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
  • 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 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
  • 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; 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
  • 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 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
  • 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 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
  • 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 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
  • 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