Download - Collections in-csharp
LAKSHMI MAREDDY
CIS525, BELLEVUE UNIVERSITY, NE
INSTRUCTOR: PROF. STUTTE
COLLECTIONS IN C#
PRESENTATION CONTENT1. Concepts Recap
2. What is a collection?
3. Types of Collection
4. Example
5. References
04/12/2023 Lakshmi Mareddy CIS525 Bellevue University NE 2
Stacks and Heaps
Value and reference
Interfaces
1. CONCEPTS RECAP
04/12/2023 Lakshmi Mareddy CIS525 Bellevue University NE 3
1.1 STACK AND HEAP MEMORY
TEMPORARY MEMORY
STACKStores 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.
Method’s (function’s) variables etc. are also stored in stack, but not in heap, and destroyed after use.
HEAPContains •attributes, •constructors and •methods of a class / object
Invoke a method in a
heap
Heap also sits in stack
04/12/2023 Lakshmi Mareddy CIS525 Bellevue University NE 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!}
04/12/2023 Lakshmi Mareddy CIS525 Bellevue University NE 5
An interface contains only the
signatures of
methods,
delegates
or events.
The implementation of the
methods is done in the class
that implements the interface
1.2 SYSTEM INTERFACES IN C#
interface ISampleInterface { void SampleMethod(); }
class ImplementationClass : ISampleInterface {
// Explicit interface member implementation: void ISampleInterface.SampleMethod() {
// Method implementation. }
static void Main() {
// Declare an interface instance. ISampleInterface obj = new ImplementationClass(); // Call the member. obj.SampleMethod();
} }
Defining an interface offers a new dimension of flexibility (Anyone implementing the interface can change the way the members are coded.) while keeping things standard so code will still be uniform. This, in turn, provides a guarantee that the code won't break when new methods are coded against the same interface.
04/12/2023 Lakshmi Mareddy CIS525 Bellevue University NE 6
Collections are enumerable data structures that can be assessed using indexes or keys.
In plain English, it is a list, with an index, to access the list.
In programming terms, we are looking at an array, which has an index, and can be accessed via the index
Closely related data can be handled more efficiently when grouped together into a collection.
Instead of writing separate code to handle each individual object, you can use the same code to process all the elements of a collection.
2. WHAT IS A COLLECTION?
04/12/2023 Lakshmi Mareddy CIS525 Bellevue University NE 7
2.1 SYSTEM NAMESPACE
iEnumerator
iEnumerable
iCollection
iList
iDictionary
Basic Interfaces
04/12/2023 Lakshmi Mareddy CIS525 Bellevue University NE 8
2.2 ICOLLECTION
iCollectionSystem.Collections.StackSystem.Collections.QueueSystem.Collections.BitArraySystem.Collections.Specialized.NameValueCollection
04/12/2023 Lakshmi Mareddy CIS525 Bellevue University NE 9
2.2.1 QUEUE
using System;
using System.Collections;
class Test
{
static void Main()
{
Queue queueObject = new Queue();
queueObject.Enqueue(“Peter");
queueObject.Enqueue(“Tony");
queueObject.Enqueue(“Ralph");
while (queueObject.Count > 0)
Console.WriteLine(queueObject.Dequeue());
Console.ReadLine();
}
}
The Enqueue() method is responsible for storing items at the rear of the Queue
The Dequeue() removes them one at a time from the front of the Queue
The Queue is a data structure that provides a First-in-First-Out collection of items of the System.Object type.
04/12/2023 Lakshmi Mareddy CIS525 Bellevue University NE 10
2.3 ILIST
iListSystem.ArraySystem.Collections.ArrayListSystem.Collections.Specialized.StringCollection
The iList interface represents collections that only have value.
04/12/2023 Lakshmi Mareddy CIS525 Bellevue University NE 11
2.3.1 ARRAYLIST EXAMPLE
using System; using System.Collections; class Test {
static void Main() {
int i = 100; double d = 20.5; ArrayList arrayList = new ArrayList(); arrayList.Capacity = 2; arrayList.Add(“Peter"); arrayList.Add(i); arrayList.Add(d); for (int index = 0; index <arrayList.Count; index++)
Console.WriteLine(arrayList[index]); }
}
The initial capacity of an ArrayList is 16, which is increased once the 17th item is stored onto it.
This repeated memory allocation and copying of the items can be quite expensive in some situations.
If we explicitly set the initial size, then we can improve performance.
04/12/2023 Lakshmi Mareddy CIS525 Bellevue University NE 12
2.4 IDICTIONARY
iDictionarySystem.Collections.SortedList System.Collections.HashtableSystem.Collections.Specialized.HybridDictionarySystem.Collections.Specialized.ListDictionary
The iDictionary interface represents collections that have name value pairs.
A Lives at #22, Wisteria Lane
Code 0 Is color Red Index to another collection
Obj X Looks at Address Book List (Home)
04/12/2023 Lakshmi Mareddy CIS525 Bellevue University NE 13
2.4.1 EXAMPLE
using System;
using System.Collections;
using System.Collections.Specialized;
class Test
{
static void Main()
{ StringDictionary stringList = newStringDictionary();
stringList.Add("A", “Ralph"); stringList.Add("B",“China"); stringList.Add("C","Jini"); stringList.Add("D",“Evan");
foreach (string str in stringList.Values) {
Console.WriteLine(str); }
}
}
Similar to the StringCollection class.
StringDictionary class, is a Hashtable that has its keys as strings only.
A Hashtable can contain any object type in its key.
04/12/2023 Lakshmi Mareddy CIS525 Bellevue University NE 14
2.5 IENUMERATOR
Enumerators only read data in the collection; they cannot be used to modify the underlying collection.
Example: C# foreach statementCounts 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 AREAWHERE CHANGES
HAPPEN
Moves implicitly through the list
04/12/2023 Lakshmi Mareddy CIS525 Bellevue University NE 15
2.6 IENUMERATOR
String names[]=new String[2] {”Rodney”,”Stutte”,”Cass”}; for(IEnumerator e =names.GetEnumerator();e.MoveNext();Response.Write(e.Current));
CURRENT, MOVENEXT, RESETOutput:RodneyStutteCass
Moves explicitly through the listVia e.MoveNext();
04/12/2023 Lakshmi Mareddy CIS525 Bellevue University NE 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.
04/12/2023 Lakshmi Mareddy CIS525 Bellevue University NE 17
Sequential List
Index Access
Key/Value or both
Sortable List
Fast Searches
Only String Type
3 WHAT TYPE OF COLLECTION?
04/12/2023 Lakshmi Mareddy CIS525 Bellevue University NE 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.
04/12/2023 Lakshmi Mareddy CIS525 Bellevue University NE 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.
04/12/2023 Lakshmi Mareddy CIS525 Bellevue University NE 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.
04/12/2023 Lakshmi Mareddy CIS525 Bellevue University NE 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.
04/12/2023 Lakshmi Mareddy CIS525 Bellevue University NE 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.
04/12/2023 Lakshmi Mareddy CIS525 Bellevue University NE 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.
04/12/2023 Lakshmi Mareddy CIS525 Bellevue University NE 24
Okay one final example
4. EXAMPLES
04/12/2023 Lakshmi Mareddy CIS525 Bellevue University NE 25
ONE FINAL EXAMPLE
using System;
using System.Collections;
class Program
{
static Hashtable GetHashtable()
{
// 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);
}
}
OutputTrueTrue1000
04/12/2023 Lakshmi Mareddy CIS525 Bellevue University NE 26
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
5. REFERENCES