DotNet Collections & Generics

Preview:

DESCRIPTION

DotNet Collections & Generics

Citation preview

1

2

Here in this Example, I have a Static Array of Employees initially set with the size 0. Currently No Employees are added to the Array. A function called AddNewEmployee is used to add a new Employee to the Array.

Limitation is Array is fixed in Size. So I have to think on a logic to achieve the mechanism of Adding Employees to the current set, without loosing my old Data. How?

• I need to create a Temporary Array of size bigger by one.

• Then Copy the Original Array into this new Temp Array created with last element being null(As this temp is bigger by one).

• Associate the new Employee object to the Last element of the temp Array.

• ReInitialize the Original Array to the Temp Array size.

• ReCopy the Temp Array Contents with the New Element to the Resized Array.

3

See how the Add Method will help to add the Element into a Collection. This is simple, easy to work with, less code.

4

5

6

The principal benefit of collections is that they standardize the way groups of objects are handled by your programs. All collections are designed around a set of clearly defined interfaces. Several built-in implementations of these interfaces, such as ArrayList, Hashtable, Stack, and Queue, are provided, which you can use as-is. You can also implement your own collection, but you will rarely need to.

• The non-generic collections implement several fundamental data structures, including a dynamic array, stack, and queue. They also include dictionaries, in which you can store key/ value pairs. An essential point to understand about the non-generic collections is that they operate on data of type object. Thus, they can be used to store any type of data, and different types of data can be mixed within the same collection. Of course, because they store object references, they are not type-safe. The non-generic collection classes and interfaces are in System.Collections.

• The specialized collections operate on a specific type of data or operate in a unique way. For example, there are specialized collections for strings. There are also specialized collections that use a singly linked list. The specialized collections are declared in System.Collections.Specialized.

7

8

9

10

11

12

13

14

Some of the Important Methods:

Add->Adds the Element to the Last of the list.

Remove->Removes the Specified Element from the List.

Find->Takes a Delegate called Predicate that evaluates an Expression on the Find Criteria and returns the found Element else returns null

ToArray->Coverts the List to a fixed size Array.

Important Properties:

Capacity->Initiailizes the size of the list

Count->Current size of the List, if new element is added, the count increases.

NOTE: If the capacity has reached while adding, the Capacity automatically increments by the no of elements you have added to the List.

15

16

17

Dictionaries represent a sophisticated data structure that allows you to access an element based on a

key. Dictionaries are also known as hash tables or maps. The main feature of dictionaries is fast lookup

based on keys. You can also add and remove items freely, a bit like a List < T > , but without the

performance overhead of having to shift subsequent items in memory.

NOTE: keys are unique to the Collection, value can be same. If u want to access the elements, you could access it by the Key name instead of Index that is used in List<T>. It is also performance based if you want to store a pairs of data in which one section needs to be unique.

18

The Dictionary class has methods to Add, Remove, Check for Key, Check for Value.

The Properties:

• Keys gets total Keys associated within the Collection.

• Values gets the Complete Collection of Values associated within the Collection

The Methods:

• ContainsKey returns True if the Key already exists else returns False

• ContainsValue returns True if the Value already exists else returns False.

19

20

21

22

HashSet<T> implements a set in which all elements are unique. In other words, duplicates are not allowed. The order of the elements is not

specified. HashSet<T> defines a full complement of set operations, such as intersection, union, and symmetric difference. This makes HashSet<T> the perfect choice for working with sets of objects. HashSet<T> is a dynamic collection that grows as needed to

accommodate the elements it must store.

23

24

25

26

Stack: To visualize a stack, imagine a stack of plates on a table. The first plate put down is the last one to be picked up. The stack is one of the most important data structures in computing. It is frequently used in system software, compilers, and AI-based backtracking routines, to name just a few.

Reference:

http://msdn.microsoft.com/en-us/library/system.collections.generic(v=VS.90).aspx

EBook:

Professional C#, Chapter 10.

27

Queue:That is, the first item put in a queue is the first item retrieved. Queues are common in real life. For example, lines at a bank or fast-food restaurant are queues. In programming, queues are used to hold such things as the currently executing processes in the system, a list of pending database transactions, or data packets received over the Internet. They are also often used in simulations.

28

29

30

An Ability to iterate is achieved when UR Class Implements IEnumerable.

IEnumerable—is used to specify that the implementing class contains data that can be enumerated.

The interface has only one function called GetEnumerator. This function returns an interface object which has methods and properties to access the individual objects of the Collection. So we know that a Collection is an object which allows to access individual object within it with a simple iteration. So if UR class implements this mechanism, then your class is a Collection class because, it returns IEnumerator which is used to iterate using Methods like MoveNext to move to the next element and access current element using Read only Current.

NOTE:

• We have only MoveNext() , Nothing like MovePrevious()=>This is Forward only.

• Current is Read Only Property.

• Is this similar to what UR foreach is doing?

From this we understand that, the Application of foreach is done using IEnumerator. This also reconfirms that foreach could be applied on Collections, so simply put, foreach is applicable on any object whose class implements IEnumerable.

31

One of the cool and yet most unknown feature of the C# is the yield keyword.

The yield keyword is used in an iterator block to provide a value to the enumerator object or to signal the end of the iteration. When used the expression is evaluated and returned as a value to the enumerator object. Note the expression has to be implicitebly convertible to yield type of the iterator.

32

The IList is the Descendent of ICollection which is the base interface for all generic Lists of .NET.

• Insert method inserts the element at the specified Index.

• RemoveAt removes an Element from the specified Index.

• Supports all the methods of ICollection like Add, Clear, Remove…….

33

Sort uses the object’s CompareTo method to compare it with other objects and uses its return value to determine which should come first.

34

Here 2 objects of the same type are compared, when equal you return 0, if x is greatedthan y, you return 1, else you return -1. Based on the return value, the Sort function of the IList interface would place the elements in the order.

35

This Example covers the Complete Implementation of a Custom Collection of Employee objects called MyCollection that has methods to Add, Remove, Find. It also has methods to Iterate, Indexer to access the Collection thro a Subscript operator.

36

37

38

39

40

41

Reference

42

43