Chapter 20 - Generic Collections

Embed Size (px)

DESCRIPTION

j

Citation preview

  • Generic Collections 1C# 30

    C# 3.0C# 3.0

    Chapter 20 Generic Collections

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    IntroductionGeneric Collections 2C# 30

    IntroductionThe BCL pro ides collection classes to The BCL provides collection classes to hold groups of objects in-memoryg p j y Each collection type is unique by representing its own

    data structure to hold objectsdata structure to hold objects Collections are encapsulated in such a way that the

    underlying data structure cant be alteredunderlying data structure can t be altered

    The .NET Framework 2.0 introduces generic Enumerators and an iteratormechanismmechanism

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Generic CollectionsGeneric Collections 3C# 30

    Generic CollectionsType DescriptionType DescriptionDictionary Represents a collection of keys and values.Li k dLi t T R t d bl li k d li tLinkedList Represents a doubly linked list.List Represents a strongly typed list of objects

    that can be accessed by indexthat can be accessed by index.

    Queue Represents a first-in, first-out collection of objects.

    SortedDictionary Represents a collection of key/value pairs that are sorted on the key.

    f /SortedList Represents a collection of key/value pairs that are sorted by key.

    Stack Represents a variable size last-in-first-outStack Represents a variable size last in first out (LIFO) collection of instances of the same arbitrary type.

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    Using Generic CollectionsGeneric Collections 4C# 30

    Using Generic Collections

    Dictionarycustomers=newDictionary();

    customers.Add("Meg",newCustomer("Meg","Ryan"));customers.Add("George",newCustomer("George",

    "Cl "))"Clooney"));customers.Add("Brad",newCustomer("Brad","Pitt"));Customercustomer customers["Brad"];Customercustomer=customers["Brad"];//IteratorsareusedtoiterateagenericcollectionIEnumerableiterator=customers Values;IEnumerableiterator=customers.Values;Listtemp=newList(iterator);temp Sort(Customer FirstName);temp.Sort(Customer.FirstName);

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • IteratorsGeneric Collections 5C# 30

    Iterators Iterators are generic types used to iterate Iterators are generic types used to iterate

    an encapsulated Collection Each one of the Generic Collections is

    provided with an Iteratorprovided with an Iterator An iterator can be used as the body of a y

    method, operator, or get accessor The return type of an iterator must be one

    of the following interfaces:of the following interfaces: IEnumerable,IEnumerator,IEnumerable,

    IEnumerator

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    IEnumerator

    Iterator TypesGeneric Collections 6C# 30

    Iterator Types There are two types of an iterator: There are two types of an iterator:

    Unnamed iterator (most common)Named iterator Named iterator

    SolarSystemPlanets planets=newSolarSystemPlanets();//Unnamediteratorforeach (stringplanetinplanets)

    Console WriteLine(planet);Console.WriteLine(planet);//Namediterator (iterator method)foreach (stringplanetinplanets Iterator(3 6))foreach (stringplanetinplanets.Iterator(3,6))

    Console.WriteLine(planet);//Namediterator (throughaproperty)//Namediterator (throughaproperty)SolarSystem solarSystem =newSolarSystem();foreach (stringplanetinsolarSystem.Planets)

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    Console.WriteLine(planet);

  • Creating an IteratorGeneric Collections 7C# 30

    Creating an Iterator Iterators specify the return values by using Iterators specify the return values by using

    the yieldreturn statementpublicIEnumerator GetEnumerator(){{

    foreach (stringplanetinplanets)yieldreturnplanet;y p ;

    }

    Alternatively, you can implement IEnumerable and IEnumerator by hand much more tedious!

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    Creating an Iterator (cont )Generic Collections 8C# 30

    Creating an Iterator (cont.)publicclassSolarSystemPlanets:IenumerablepublicclassSolarSystemPlanets:Ienumerable{

    privatestring[]_planets= ...;bli IE t G tE t ()publicIEnumeratorGetEnumerator()

    {foreach(stringplanetin planets)foreach(stringplanetin_planets)

    yieldreturnplanet;}

    bli IE bl t i It t (publicIEnumerableIterator(int start,intend)

    {{for(inti=start;i

  • Generic Type IteratorGeneric Collections 9C# 30

    Generic Type IteratorpublicclassGenericCollectionpublicclassGenericCollection{

    privateT[]_items;

    publicGenericCollection(int count){{

    _items=newT[count];}...publicIEnumerator GetEnumerator(){{

    foreach (Titemin_items){

    i ld t ityieldreturnitem;}

    }

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    }}

    Collection InitializersGeneric Collections 10C# 30

    Collection InitializersArra s ha e a nati e and con enient Arrays have a native and convenient initialization syntax

    i t[]fi tP i {2 3 5 7}

    y Why not any collection?

    int[]firstPrimes ={2,3,5,7};Listnums =newList{

    5 3 205,3,20};Dictionarydict =

    Becomes

    Dictionarydict =newDictionary{

    {A,1},{ , },{B,2}

    };

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Collection Initializers NotesGeneric Collections 11C# 30

    Collection Initializers NotesThe pattern orks for an IC ll ti T The pattern works for any ICollection It calls Add(T) for each element

    It also works for any IEnumerable that also It also works for any IEnumerable that also has an Add method

    If h f l dd If you have a range of elements to add, prefer built-in AddRange methodsprefer built in AddRange methods (performance)

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    Generic Collections 12C# 30

    Chapter 20 Exercise 1

    IMPLEMENTING A GENERIC COLLECTIONCOLLECTION

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • SummaryGeneric Collections 13C# 30

    SummaryGeneric collections are efficient t pe safe Generic collections are efficient, type safe data structures

    Collections and types can be iterated with th C# f h k d i it tthe C# foreach keyword using an iterator The iterator code specifies how return values are p

    generated when the foreach loop accesses each element of the collection

    Iterators simplify the process of implementing IEnumerable or IEnumerator methods

    Iterators allowing you to concentrate on writing the iteration code rather implementing IEnumerator

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    iteration code rather implementing IEnumerator