SlideShare a Scribd company logo
collection types in C#.
• The .NET framework provides specialized classes for data storage
  and retrieval. In one of the previous chapters, we have described
  arrays. Collections are enhancement to the arrays.
• There are two distinct collection types in C#.
 The standard collections, which are found under the
  System.Collections namespace and
 the generic collections, under System.Collections.Generic.
• The generic collections are more flexible and are the preferred way
  to work with data. The generic collections or generics were
  introduced in .NET framework 2.0. Generics enhance code reuse,
  type safety, and performance.
• Generic programming is a style of computer programming in which
  algorithms are written in terms of to-be-specified-later types that
  are then instantiated when needed for specific types provided as
  parameters.
ArrayList
• ArrayList is a collection from a standard System.Collections
   namespace.
• It is a dynamic array. It provides random access to its elements.
• An ArrayList automatically expands as data is added. Unlike arrays,
   an ArrayList can hold data of multiple data types.
• Elements in the ArrayList are accessed via an integer index. Indexes
   are zero based. Indexing of elements and insertion and deletion at
   the end of the ArrayList takes constant time. Inserting or deleting
   an element in the middle of the dynamic array is more costly. It
   takes linear time.
using System;
 using System.Collections;
public class CSharpApp
{
class Empty {}
ArrayList
static void Main()
{
ArrayList da = new ArrayList();
da.Add("Visual Basic");
 da.Add(344);
da.Add(55);
 da.Add(new Empty());
da.Remove(55);
foreach(object el in da)
{
Console.WriteLine(el);
 }}}
ArrayList
In the above example, we have created an ArrayList collection. We
    have added some elements to it. They are of various data
    type, string, int and a class object.
using System.Collections;
         In order to work with ArrayList collection, we need to import
         System.Collections namespace.
ArrayList da = new ArrayList();
         An ArrayList collection is created.
da.Add("Visual Basic");
da.Add(344);
da.Add(55);
da.Add(new Empty()); da.Remove(55); We add five elements to the
    array with the Add() method.
da.Remove(55); We remove one element.
List
• A List is a strongly typed list of objects that can be accessed by
    index. It can be found under System.Collections.Generic
    namespace.
using System;
 using System.Collections.Generic;
 public class CSharpApp
 {
static void Main()
 {
 List<string> langs = new List<string>();
 langs.Add("Java");
langs.Add("C#");
langs.Add("C");
langs.Add("C++");
List
langs.Add("Ruby");
 langs.Add("Javascript");
Console.WriteLine(langs.Contains("C#"));
Console.WriteLine(langs[1]);
Console.WriteLine(langs[2]);
langs.Remove("C#");
langs.Remove("C");
Console.WriteLine(langs.Contains("C#"));
 langs.Insert(4, "Haskell");
langs.Sort();
 foreach(string lang in langs)
 {
Console.WriteLine(lang);
}}}
List
In the preceding example, we work with the List collection.
using System.Collections.Generic;
    In order to work with the List collection, we need to import
   the System.Collections.Generic namespace.
List<string> langs = new List<string>();
   A generic dynamic array is created. We specify that we will
   work with strings with the type specified inside <>
   characters.
• langs.Add("Java");
• langs.Add("C#");
• langs.Add("C"); ... We add elements to the List using the
   Add() method.
List
• Console.WriteLine(langs.Contains("C#")); We check if
  the List contains a specific string using the Contains()
  method.
• Console.WriteLine(langs[1]);
  Console.WriteLine(langs[2]); We access the second and
  the third element of the List using the index notation.
• langs.Remove("C#"); langs.Remove("C"); We remove
  two strings from the List.
• langs.Insert(4, "Haskell"); We insert a string at a
  specific location.
• langs.Sort(); We sort the elements using the Sort()
  method.
LinkedList
•   LinkedList is a generic doubly linked list in C#.
•   LinkedList only allows sequential access.
•   LinkedList allows for constant-time insertions or removals, but only sequential
    access of elements. Because linked lists need extra storage for references, they are
    impractical for lists of small data items such as characters.
• Unlike dynamic arrays, arbitrary number of items can be added to the linked list
    (limited by the memory of course) without the need to realocate, which is an
    expensive operation.
using System;
using System.Collections.Generic;
public class CSharpApp
 {
static void Main()
{
 LinkedList<int> nums = new LinkedList<int>(); nums.AddLast(23);
LinkedList

nums.AddLast(34);
 nums.AddLast(33);
 nums.AddLast(11);
nums.AddLast(6);
nums.AddFirst(9);
nums.AddFirst(7);
LinkedListNode<int> node = nums.Find(6);
nums.AddBefore(node, 5);
foreach(int num in nums)
 {
Console.WriteLine(num); } } }
This is a LinkedList example with some of its methods.
LinkedList
• LinkedList<int> nums = new LinkedList<int>(); This is an
  integer LinkedList.
• nums.AddLast(23); ... nums.AddFirst(7); We populate
  the linked list using the AddLast() and AddFirst()
  methods.
• LinkedListNode<int> node = nums.Find(6);
  nums.AddBefore(node, 5); A LinkedList consists of
  nodes. We find a specific node and add an element
  before it.
• foreach(int num in nums) { Console.WriteLine(num); }
  Printing all elements to the console.
Dictionary

• A dictionary, also called an associative array, is a collection
   of unique keys and a collection of values, where each key is
   associated with one value.
• Retrieving and adding values is very fast. Dictionaries take
   more memory, because for each value there is also a key.
using System;
using System.Collections.Generic;
public class CSharpApp
{
static void Main()
 {
Dictionary
Dictionary<string, string> domains = new Dictionary<string,
   string>(); domains.Add("de", "Germany");
 domains.Add("sk", "Slovakia");
domains.Add("us", "United States");
domains.Add("ru", "Russia");
domains.Add("hu", "Hungary");
 domains.Add("pl", "Poland");
 Console.WriteLine(domains["sk"]);
Console.WriteLine(domains["de"]);
Console.WriteLine("Dictionary has {0} items", domains.Count);
Console.WriteLine("Keys of the dictionary:");
List<string> keys = new List<string>(domains.Keys);
Dictionary
foreach(string key in keys)
{
Console.WriteLine("{0}", key);
}
 Console.WriteLine("Values of the dictionary:");
List<string> vals = new List<string>(domains.Values);
foreach(string val in vals)
{
Console.WriteLine("{0}", val);
}
Console.WriteLine("Keys and values of the dictionary:");
 foreach(KeyValuePair<string, string> kvp in domains)
 {
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
 }}}
Dictionary
We have a dictionary, where we map domain names to their country names.
Dictionary<string, string> domains = new Dictionary<string, string>();
We create a dictionary with string keys and values.
• domains.Add("de", "Germany");
• domains.Add("sk", "Slovakia");
• domains.Add("us", "United States"); ... We add some data to the
   dictionary. The first string is the key. The second is the value.
• Console.WriteLine("Dictionary has {0} items", domains.Count); We print
   the number of items by referring to the Count property.
• List<string> keys = new List<string>(domains.Keys);
• List<string> vals = new List<string>(domains.Values); foreach(string val in
   vals) { Console.WriteLine("{0}", val); } These lines retrieve all values from
   the dictionary.
• foreach(KeyValuePair<string, string> kvp in domains) {
   Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); } Finally, we
   print both keys and values of the dictionary.
Queues

• A queue is a First-In-First-Out (FIFO) data structure. The first
  element added to the queue will be the first one to be removed.
  Queues may be used to process messages as they appear or serve
  customers as they come. The first customer which comes should be
  served first.
• using System;
• using System.Collections.Generic;
• public class CSharpApp
• {
• static void Main()
• {
• Queue<string> msgs = new Queue<string>();
Queues
•   msgs.Enqueue("Message 1");
•    msgs.Enqueue("Message 2");
•   msgs.Enqueue("Message 3");
•    msgs.Enqueue("Message 4");
•   msgs.Enqueue("Message 5");
•   Console.WriteLine(msgs.Dequeue());
•    Console.WriteLine(msgs.Peek());
•   Console.WriteLine(msgs.Peek());
•   Console.WriteLine();
•    foreach(string msg in msgs)
•   {
•   Console.WriteLine(msg);
•   }}}
Queues
• In our example, we have a queue with messages.
• Queue<string> msgs = new Queue<string>(); A queue
  of strings is created.
• msgs.Enqueue("Message 1"); msgs.Enqueue("Message
  2"); ... The Enqueue() adds a message to the end of the
  queue.
• Console.WriteLine(msgs.Dequeue()); The Dequeue()
  method removes and returns the item at the beginning
  of the queue.
• Console.WriteLine(msgs.Peek()); The Peek() method
  returns the next item from the queue, but does not
  remove it from the collection.
Stacks
• A stack is a Last-In-First-Out (LIFO) data structure.
• The last element added to the queue will be the first one to
  be removed.
• The C language uses a stack to store local data in a function.
  The stack is also used when implementing calculators.
• using System;
• using System.Collections.Generic;
• public class CSharpApp
• {
• static void Main()
• {
• Stack<int> stc = new Stack<int>();
Stacks
•   stc.Push(1);
•   stc.Push(4);
•   stc.Push(3);
•   stc.Push(6);
•    stc.Push(4);
•   Console.WriteLine(stc.Pop());
•   Console.WriteLine(stc.Peek());
•   Console.WriteLine(stc.Peek());
•   Console.WriteLine();
•   foreach(int item in stc)
•   {
•   Console.WriteLine(item);
•   } } } We have a simple stack
Stacks
• example above.
• Stack<int> stc = new Stack<int>(); A Stack data
  structure is created.
• stc.Push(1); stc.Push(4); ... The Push() method adds an
  item at the top of the stack.
• Console.WriteLine(stc.Pop()); The Pop() method
  removes and returns the item from the top of the
  stack.
• Console.WriteLine(stc.Peek()); The Peek() method
  returns the item from the top of the stack. It does not
  remove it.
• 4 6 6 6 3 4 1 Output.

More Related Content

What's hot

Functional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and StreamsFunctional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and Streams
CodeOps Technologies LLP
 
Spark Schema For Free with David Szakallas
 Spark Schema For Free with David Szakallas Spark Schema For Free with David Szakallas
Spark Schema For Free with David Szakallas
Databricks
 
Collections
CollectionsCollections
Collections
Rajkattamuri
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
Sunil OS
 
Collections
CollectionsCollections
Collections
Manav Prasad
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
Tomer Gabel
 
Scala Collections : Java 8 on Steroids
Scala Collections : Java 8 on SteroidsScala Collections : Java 8 on Steroids
Scala Collections : Java 8 on Steroids
François Garillot
 
Java Language fundamental
Java Language fundamentalJava Language fundamental
Java Language fundamental
Infoviaan Technologies
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
Array list
Array listArray list
Array list
vishal choudhary
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arrays
Hassan Dar
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
Shalabh Chaudhary
 
Collections in .net technology (2160711)
Collections in .net technology (2160711)Collections in .net technology (2160711)
Collections in .net technology (2160711)
Janki Shah
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
Hugo Gävert
 
Scalding - Hadoop Word Count in LESS than 70 lines of code
Scalding - Hadoop Word Count in LESS than 70 lines of codeScalding - Hadoop Word Count in LESS than 70 lines of code
Scalding - Hadoop Word Count in LESS than 70 lines of code
Konrad Malawski
 
Scalding: Twitter's Scala DSL for Hadoop/Cascading
Scalding: Twitter's Scala DSL for Hadoop/CascadingScalding: Twitter's Scala DSL for Hadoop/Cascading
Scalding: Twitter's Scala DSL for Hadoop/Cascading
johnynek
 
ComputeFest 2012: Intro To R for Physical Sciences
ComputeFest 2012: Intro To R for Physical SciencesComputeFest 2012: Intro To R for Physical Sciences
ComputeFest 2012: Intro To R for Physical Sciences
alexstorer
 
Apache avro and overview hadoop tools
Apache avro and overview hadoop toolsApache avro and overview hadoop tools
Apache avro and overview hadoop tools
alireza alikhani
 
Should I Use Scalding or Scoobi or Scrunch?
Should I Use Scalding or Scoobi or Scrunch? Should I Use Scalding or Scoobi or Scrunch?
Should I Use Scalding or Scoobi or Scrunch?
DataWorks Summit
 
Scala introduction
Scala introductionScala introduction
Scala introduction
vito jeng
 

What's hot (20)

Functional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and StreamsFunctional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and Streams
 
Spark Schema For Free with David Szakallas
 Spark Schema For Free with David Szakallas Spark Schema For Free with David Szakallas
Spark Schema For Free with David Szakallas
 
Collections
CollectionsCollections
Collections
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
 
Collections
CollectionsCollections
Collections
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
Scala Collections : Java 8 on Steroids
Scala Collections : Java 8 on SteroidsScala Collections : Java 8 on Steroids
Scala Collections : Java 8 on Steroids
 
Java Language fundamental
Java Language fundamentalJava Language fundamental
Java Language fundamental
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Array list
Array listArray list
Array list
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arrays
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
Collections in .net technology (2160711)
Collections in .net technology (2160711)Collections in .net technology (2160711)
Collections in .net technology (2160711)
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
 
Scalding - Hadoop Word Count in LESS than 70 lines of code
Scalding - Hadoop Word Count in LESS than 70 lines of codeScalding - Hadoop Word Count in LESS than 70 lines of code
Scalding - Hadoop Word Count in LESS than 70 lines of code
 
Scalding: Twitter's Scala DSL for Hadoop/Cascading
Scalding: Twitter's Scala DSL for Hadoop/CascadingScalding: Twitter's Scala DSL for Hadoop/Cascading
Scalding: Twitter's Scala DSL for Hadoop/Cascading
 
ComputeFest 2012: Intro To R for Physical Sciences
ComputeFest 2012: Intro To R for Physical SciencesComputeFest 2012: Intro To R for Physical Sciences
ComputeFest 2012: Intro To R for Physical Sciences
 
Apache avro and overview hadoop tools
Apache avro and overview hadoop toolsApache avro and overview hadoop tools
Apache avro and overview hadoop tools
 
Should I Use Scalding or Scoobi or Scrunch?
Should I Use Scalding or Scoobi or Scrunch? Should I Use Scalding or Scoobi or Scrunch?
Should I Use Scalding or Scoobi or Scrunch?
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 

Similar to Collection

C# p9
C# p9C# p9
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
Sandeep Kr. Singh
 
4java Basic Syntax
4java Basic Syntax4java Basic Syntax
4java Basic Syntax
Adil Jafri
 
Aggregate.pptx
Aggregate.pptxAggregate.pptx
Aggregate.pptx
Ramakrishna Reddy Bijjam
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
Prof. Erwin Globio
 
Collections
CollectionsCollections
Collections
sagsharma
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
Haitham El-Ghareeb
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
Sandesh Sharma
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
shinolajla
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
Michael Heron
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
Knoldus Inc.
 
Java 103
Java 103Java 103
Java 103
Manuela Grindei
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
Khasim Cise
 
Real Time Big Data Management
Real Time Big Data ManagementReal Time Big Data Management
Real Time Big Data Management
Albert Bifet
 
Data structures
Data structuresData structures
Data structures
Nur Saleha
 
stack.ppt
stack.pptstack.ppt
stack.ppt
ssuserec1395
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
IndicThreads
 
Ds
DsDs
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
AnkitaVerma776806
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
agorolabs
 

Similar to Collection (20)

C# p9
C# p9C# p9
C# p9
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
4java Basic Syntax
4java Basic Syntax4java Basic Syntax
4java Basic Syntax
 
Aggregate.pptx
Aggregate.pptxAggregate.pptx
Aggregate.pptx
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Collections
CollectionsCollections
Collections
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 
Java 103
Java 103Java 103
Java 103
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
 
Real Time Big Data Management
Real Time Big Data ManagementReal Time Big Data Management
Real Time Big Data Management
 
Data structures
Data structuresData structures
Data structures
 
stack.ppt
stack.pptstack.ppt
stack.ppt
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
Ds
DsDs
Ds
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
 

Recently uploaded

The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
Celine George
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 

Recently uploaded (20)

The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 

Collection

  • 1. collection types in C#. • The .NET framework provides specialized classes for data storage and retrieval. In one of the previous chapters, we have described arrays. Collections are enhancement to the arrays. • There are two distinct collection types in C#.  The standard collections, which are found under the System.Collections namespace and  the generic collections, under System.Collections.Generic. • The generic collections are more flexible and are the preferred way to work with data. The generic collections or generics were introduced in .NET framework 2.0. Generics enhance code reuse, type safety, and performance. • Generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters.
  • 2. ArrayList • ArrayList is a collection from a standard System.Collections namespace. • It is a dynamic array. It provides random access to its elements. • An ArrayList automatically expands as data is added. Unlike arrays, an ArrayList can hold data of multiple data types. • Elements in the ArrayList are accessed via an integer index. Indexes are zero based. Indexing of elements and insertion and deletion at the end of the ArrayList takes constant time. Inserting or deleting an element in the middle of the dynamic array is more costly. It takes linear time. using System; using System.Collections; public class CSharpApp { class Empty {}
  • 3. ArrayList static void Main() { ArrayList da = new ArrayList(); da.Add("Visual Basic"); da.Add(344); da.Add(55); da.Add(new Empty()); da.Remove(55); foreach(object el in da) { Console.WriteLine(el); }}}
  • 4. ArrayList In the above example, we have created an ArrayList collection. We have added some elements to it. They are of various data type, string, int and a class object. using System.Collections; In order to work with ArrayList collection, we need to import System.Collections namespace. ArrayList da = new ArrayList(); An ArrayList collection is created. da.Add("Visual Basic"); da.Add(344); da.Add(55); da.Add(new Empty()); da.Remove(55); We add five elements to the array with the Add() method. da.Remove(55); We remove one element.
  • 5. List • A List is a strongly typed list of objects that can be accessed by index. It can be found under System.Collections.Generic namespace. using System; using System.Collections.Generic; public class CSharpApp { static void Main() { List<string> langs = new List<string>(); langs.Add("Java"); langs.Add("C#"); langs.Add("C"); langs.Add("C++");
  • 7. List In the preceding example, we work with the List collection. using System.Collections.Generic; In order to work with the List collection, we need to import the System.Collections.Generic namespace. List<string> langs = new List<string>(); A generic dynamic array is created. We specify that we will work with strings with the type specified inside <> characters. • langs.Add("Java"); • langs.Add("C#"); • langs.Add("C"); ... We add elements to the List using the Add() method.
  • 8. List • Console.WriteLine(langs.Contains("C#")); We check if the List contains a specific string using the Contains() method. • Console.WriteLine(langs[1]); Console.WriteLine(langs[2]); We access the second and the third element of the List using the index notation. • langs.Remove("C#"); langs.Remove("C"); We remove two strings from the List. • langs.Insert(4, "Haskell"); We insert a string at a specific location. • langs.Sort(); We sort the elements using the Sort() method.
  • 9. LinkedList • LinkedList is a generic doubly linked list in C#. • LinkedList only allows sequential access. • LinkedList allows for constant-time insertions or removals, but only sequential access of elements. Because linked lists need extra storage for references, they are impractical for lists of small data items such as characters. • Unlike dynamic arrays, arbitrary number of items can be added to the linked list (limited by the memory of course) without the need to realocate, which is an expensive operation. using System; using System.Collections.Generic; public class CSharpApp { static void Main() { LinkedList<int> nums = new LinkedList<int>(); nums.AddLast(23);
  • 10. LinkedList nums.AddLast(34); nums.AddLast(33); nums.AddLast(11); nums.AddLast(6); nums.AddFirst(9); nums.AddFirst(7); LinkedListNode<int> node = nums.Find(6); nums.AddBefore(node, 5); foreach(int num in nums) { Console.WriteLine(num); } } } This is a LinkedList example with some of its methods.
  • 11. LinkedList • LinkedList<int> nums = new LinkedList<int>(); This is an integer LinkedList. • nums.AddLast(23); ... nums.AddFirst(7); We populate the linked list using the AddLast() and AddFirst() methods. • LinkedListNode<int> node = nums.Find(6); nums.AddBefore(node, 5); A LinkedList consists of nodes. We find a specific node and add an element before it. • foreach(int num in nums) { Console.WriteLine(num); } Printing all elements to the console.
  • 12. Dictionary • A dictionary, also called an associative array, is a collection of unique keys and a collection of values, where each key is associated with one value. • Retrieving and adding values is very fast. Dictionaries take more memory, because for each value there is also a key. using System; using System.Collections.Generic; public class CSharpApp { static void Main() {
  • 13. Dictionary Dictionary<string, string> domains = new Dictionary<string, string>(); domains.Add("de", "Germany"); domains.Add("sk", "Slovakia"); domains.Add("us", "United States"); domains.Add("ru", "Russia"); domains.Add("hu", "Hungary"); domains.Add("pl", "Poland"); Console.WriteLine(domains["sk"]); Console.WriteLine(domains["de"]); Console.WriteLine("Dictionary has {0} items", domains.Count); Console.WriteLine("Keys of the dictionary:"); List<string> keys = new List<string>(domains.Keys);
  • 14. Dictionary foreach(string key in keys) { Console.WriteLine("{0}", key); } Console.WriteLine("Values of the dictionary:"); List<string> vals = new List<string>(domains.Values); foreach(string val in vals) { Console.WriteLine("{0}", val); } Console.WriteLine("Keys and values of the dictionary:"); foreach(KeyValuePair<string, string> kvp in domains) { Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); }}}
  • 15. Dictionary We have a dictionary, where we map domain names to their country names. Dictionary<string, string> domains = new Dictionary<string, string>(); We create a dictionary with string keys and values. • domains.Add("de", "Germany"); • domains.Add("sk", "Slovakia"); • domains.Add("us", "United States"); ... We add some data to the dictionary. The first string is the key. The second is the value. • Console.WriteLine("Dictionary has {0} items", domains.Count); We print the number of items by referring to the Count property. • List<string> keys = new List<string>(domains.Keys); • List<string> vals = new List<string>(domains.Values); foreach(string val in vals) { Console.WriteLine("{0}", val); } These lines retrieve all values from the dictionary. • foreach(KeyValuePair<string, string> kvp in domains) { Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); } Finally, we print both keys and values of the dictionary.
  • 16. Queues • A queue is a First-In-First-Out (FIFO) data structure. The first element added to the queue will be the first one to be removed. Queues may be used to process messages as they appear or serve customers as they come. The first customer which comes should be served first. • using System; • using System.Collections.Generic; • public class CSharpApp • { • static void Main() • { • Queue<string> msgs = new Queue<string>();
  • 17. Queues • msgs.Enqueue("Message 1"); • msgs.Enqueue("Message 2"); • msgs.Enqueue("Message 3"); • msgs.Enqueue("Message 4"); • msgs.Enqueue("Message 5"); • Console.WriteLine(msgs.Dequeue()); • Console.WriteLine(msgs.Peek()); • Console.WriteLine(msgs.Peek()); • Console.WriteLine(); • foreach(string msg in msgs) • { • Console.WriteLine(msg); • }}}
  • 18. Queues • In our example, we have a queue with messages. • Queue<string> msgs = new Queue<string>(); A queue of strings is created. • msgs.Enqueue("Message 1"); msgs.Enqueue("Message 2"); ... The Enqueue() adds a message to the end of the queue. • Console.WriteLine(msgs.Dequeue()); The Dequeue() method removes and returns the item at the beginning of the queue. • Console.WriteLine(msgs.Peek()); The Peek() method returns the next item from the queue, but does not remove it from the collection.
  • 19. Stacks • A stack is a Last-In-First-Out (LIFO) data structure. • The last element added to the queue will be the first one to be removed. • The C language uses a stack to store local data in a function. The stack is also used when implementing calculators. • using System; • using System.Collections.Generic; • public class CSharpApp • { • static void Main() • { • Stack<int> stc = new Stack<int>();
  • 20. Stacks • stc.Push(1); • stc.Push(4); • stc.Push(3); • stc.Push(6); • stc.Push(4); • Console.WriteLine(stc.Pop()); • Console.WriteLine(stc.Peek()); • Console.WriteLine(stc.Peek()); • Console.WriteLine(); • foreach(int item in stc) • { • Console.WriteLine(item); • } } } We have a simple stack
  • 21. Stacks • example above. • Stack<int> stc = new Stack<int>(); A Stack data structure is created. • stc.Push(1); stc.Push(4); ... The Push() method adds an item at the top of the stack. • Console.WriteLine(stc.Pop()); The Pop() method removes and returns the item from the top of the stack. • Console.WriteLine(stc.Peek()); The Peek() method returns the item from the top of the stack. It does not remove it. • 4 6 6 6 3 4 1 Output.