0% found this document useful (0 votes)
17 views

OOP L12 Data Structures Lite

Uploaded by

ok1484478
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

OOP L12 Data Structures Lite

Uploaded by

ok1484478
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

OOP_L12_Data Structures

e t
C# Arrays
Updated on: May 10, 2020

A variable is used to store a literal value, whereas an array is used to store multiple literal values.

An array is the data structure that stores a fixed number of literal values (elements) of the same data
type. Array elements are stored contiguously in the memory.

In C#, an array can be of three types: single-dimensional, multidimensional, and jagged array. Here
you will learn about the single-dimensional array.

The following figure illustrates an array representation.

Array Representation

Array Declaration and Initialization


An array can be declared using by specifying the type of its elements with square brackets.

Example: Array Declaration


int[] evenNums; // integer array

string[] cities; // string array

The following declares and adds values into an array in a single statement.

Example: Array Declaration & Initialization


int[] evenNums = new int[5]{ 2, 4, 6, 8, 10 };

string[] cities = new string[3]{ "Mumbai", "London", "New York" };

Above, evenNums array can store up to five integers. The number 5 in the square brackets new
int[5] specifies the size of an array. In the same way, the size of cities array is three. Array
elements are added in a comma-separated list inside curly braces { }.

Arrays type variables can be declared using var without square brackets.

Example: Array Declaration using var


var evenNums = new int[]{ 2, 4, 6, 8, 10};

var cities = new string[]{ "Mumbai", "London", "New York" };


If you are adding array elements at the time of declaration, then size is optional. The compiler will
infer its size based on the number of elements inside curly braces, as shown below.

Example: Short Syntax of Array Declaration


int[] evenNums = { 2, 4, 6, 8, 10};

string[] cities = { "Mumbai", "London", "New York" }

The following example demonstrate invalid array declarations.

Example: Invalid Array Creation


//must specify the size
int[] evenNums = new int[];

//number of elements must be equal to the specified size


int[] evenNums = new int[5] { 2, 4 };

//cannot use var with array initializer


var evenNums = { 2, 4, 6, 8, 10};

Late Initialization
It is not necessary to declare and initialize an array in a single statement. You can first declare an
array then initialize it later on using the new operator.

Example: Late Initialization


int[] evenNums;

evenNums = new int[5];


// or
evenNums = new int[]{ 2, 4, 6, 8, 10 };

Accessing Array Elements


Array elements can be accessed using an index. An index is a number associated with each array
element, starting with index 0 and ending with array size - 1.

The following example add/update and retrieve array elements using indexes.

Example: Access Array Elements using Indexes


int[] evenNums = new int[5];
evenNums[0] = 2;
evenNums[1] = 4;
//evenNums[6] = 12; //Throws run-time exception IndexOutOfRange

Console.WriteLine(evenNums[0]); //prints 2
Console.WriteLine(evenNums[1]); //prints 4

Note that trying to add more elements than its specified size will result in
IndexOutOfRangeException.
Accessing Array using for Loop
Use the for loop to access array elements. Use the length property of an array in conditional
expression of the for loop.

Example: Accessing Array Elements using for Loop


int[] evenNums = { 2, 4, 6, 8, 10 };

for(int i = 0; i < evenNums.Length; i++)


Console.WriteLine(evenNums[i]);

for(int i = 0; i < evenNums.Length; i++)


evenNums[i] = evenNums[i] + 10; // update the value of each element by 10

Accessing Array using foreach Loop


Use foreach loop to read values of an array elements without using index.

Example: Accessing Array using foreach Loop


int[] evenNums = { 2, 4, 6, 8, 10};
string[] cities = { "Mumbai", "London", "New York" };

foreach(var item in evenNums)


Console.WriteLine(item);

foreach(var city in cities)


Console.WriteLine(city);

LINQ Methods
All the arrays in C# are derived from an abstract base class System.Array.

The Array class implements the IEnumerable interface, so you can LINQ extension methods such as
Max(), Min(), Sum(), reverse(), etc. See the list of all extension methods here.

Example: LINQ Methods


int[] nums = new int[5]{ 10, 15, 16, 8, 6 };

nums.Max(); // returns 16
nums.Min(); // returns 6
nums.Sum(); // returns 55
nums.Average(); // returns 55

The System.Array class also includes methods for creating, manipulating, searching, and sorting
arrays. See list of all Array methods here.

Example: Array Methods


int[] nums = new int[5]{ 10, 15, 16, 8, 6 };

Array.Sort(nums); // sorts array


Array.Reverse(nums); // sorts array in descending order
Array.ForEach(nums, n => Console.WriteLine(n)); // iterates array
Array.BinarySearch(nums, 5);// binary search
Passing Array as Argument
An array can be passed as an argument to a method parameter. Arrays are reference types, so the
method can change the value of the array elements.

Example: Passing Array as Argument


public static void Main(){
int[] nums = { 1, 2, 3, 4, 5 };

UpdateArray(nums);

foreach(var item in nums)


Console.WriteLine(item);
}

public static void UpdateArray(int[] arr)


{
for(int i = 0; i < arr.Length; i++)
arr[i] = arr[i] + 10;
}

C# - Multidimensi nal Arrays


C# supports multidimensional arrays up to 32 dimensions. The multidimensional array can be
declared by adding commas in the square brackets. For example, [,] declares two-dimensional array,
[, ,] declares three-dimensional array, [, , ,] declares four-dimensional array, and so on. So, in a
multidimensional array, no of commas = No of Dimensions - 1.

The following declares multidimensional arrays.

Example: Multidimensional Arrays


int[,] arr2d; // two-dimensional array
int[, ,] arr3d; // three-dimensional array
int[, , ,] arr4d ; // four-dimensional array
int[, , , ,] arr5d; // five-dimensional array

Let's understand the two-dimensional array. The following initializes the two-dimensional array.

Example: two-dimensional Array


int[,] arr2d = new int[3,2]{
{1, 2},
{3, 4},
{5, 6}
};

// or
int[,] arr2d = {
{1, 2},
{3, 4},
{5, 6}
};

In the above example of a two-dimensional array, [3, 2] defines the no of rows and columns. The
first rank denotes the no of rows, and the second rank defines no of columns. The following figure
illustrates the two-dimensional array divided into rows and columns.
Two-dimensional Array

The following access values of the two-dimensional array.

Example: Access two-dimensional Array


int[,] arr2d = new int[3,2]{
{1, 2},
{3, 4},
{5, 6}
};

arr2d[0, 0]; //returns 1


arr2d[0, 1]; //returns 2
arr2d[1, 0]; //returns 3
arr2d[1, 1]; //returns 4
arr2d[2, 0]; //returns 5
arr2d[2, 1]; //returns 6
//arr2d[3, 0]; //throws run-time error as there is no 4th row

In the above example, the value of a two-dimensional array can be accessed by index no of row and
column as [row index, column index]. So, [0, 0] returns the value of the first row and first column
and [1, 1] returns the value from the second row and second column.

Now, let's understand the three-dimensional array. The following declares and initializes three-
dimensional arrays.

Example: Three-dimensional Array


int[, ,] arr3d1 = new int[1, 2, 2]{
{ { 1, 2}, { 3, 4} }
};

int[, ,] arr3d2 = new int[2, 2, 2]{


{ {1, 2}, {3, 4} },
{ {5, 6}, {7, 8} }
};

int[, ,] arr3d3 = new int[2, 2, 3]{


{ { 1, 2, 3}, {4, 5, 6} },
{ { 7, 8, 9}, {10, 11, 12} }
};

arr3d2[0, 0, 0]; // returns 1


arr3d2[0, 0, 1]; // returns 2
arr3d2[0, 1, 0]; // returns 3
arr3d2[0, 1, 1]; // returns 4
arr3d2[1, 0, 0]; // returns 5
arr3d2[1, 0, 1]; // returns 6
arr3d2[1, 1, 0]; // returns 7
arr3d2[1, 1, 1]; // returns 8
As you can see in the above example, [1, 2, 2] of arr3d1 specifies that it will contain one row of
two-dimensional array [2, 2]. arr3d2 specifies dimensions [2, 2, 2], which indicates that it includes
two rows of two-dimensional array of [2, 2]. Thus, the first rank indicates the number of rows of
inner two-dimensional arrays.

Now, consider the following four-dimensional array.

Example: Four-dimensional Array


int[,,,] arr4d1 = new int[1, 1, 2, 2]{
{
{ { 1, 2}, { 3, 4} }
}
};

arr4d1[0, 0, 0, 0]; // returns 1


arr4d1[0, 0, 0, 1]; // returns 2
arr4d1[0, 0, 1, 0]; // returns 3
arr4d1[0, 0, 1, 1]; // returns 4

int[,,,] arr4d2 = new int[1, 2, 2, 2]{


{
{ {1, 2}, {3, 4} },
{ {5, 6}, {7, 8} }
}
};

arr4d2[0, 0, 0, 0]; // returns 1


arr4d2[0, 0, 0, 1]; // returns 2
arr4d2[0, 0, 1, 0]; // returns 3
arr4d2[0, 0, 1, 1]; // returns 4
arr4d2[0, 1, 0, 0]; // returns 5
arr4d2[0, 1, 0, 1]; // returns 6
arr4d2[0, 1, 1, 0]; // returns 7
arr4d2[0, 1, 1, 1]; // returns 8

C# - ArrayList
In C#, the ArrayList is a non-generic collection of objects whose size increases dynamically. It is
the same as Array except that its size increases dynamically.

An ArrayList can be used to add unknown data where you don't know the types and the size of the
data.

Create an ArrayList
The ArrayList class included in the System.Collections namespace. Create an object of the
ArrayList using the new keyword.

Example: Create an ArrayList


using System.Collections;

ArrayList arlist = new ArrayList();


// or
var arlist = new ArrayList(); // recommended
Adding Elements in ArrayList
Use the Add() method or object initializer syntax to add elements in an ArrayList.

An ArrayList can contain multiple null and duplicate values.

Example: Adding Elements in ArrayList


// adding elements using ArrayList.Add() method
var arlist1 = new ArrayList();
arlist1.Add(1);
arlist1.Add("Bill");
arlist1.Add(" ");
arlist1.Add(true);
arlist1.Add(4.5);
arlist1.Add(null);

// adding elements using object initializer syntax


var arlist2 = new ArrayList()
{
2, "Steve", " ", true, 4.5, null
};

Use the AddRange(ICollection c) method to add an entire Array, HashTable, SortedList,


ArrayList, BitArray, Queue, and Stack in the ArrayList.

Example: Adding Entire Array/ArrayList into ArrayList


var arlist1 = new ArrayList();

var arlist2 = new ArrayList()


{
1, "Bill", " ", true, 4.5, null
};

int[] arr = { 100, 200, 300, 400 };

Queue myQ = new Queue();


myQ.Enqueue("Hello");
myQ.Enqueue("World!");

arlist1.AddRange(arlist2); //adding arraylist in arraylist


arlist1.AddRange(arr); //adding array in arraylist
arlist1.AddRange(myQ); //adding Queue in arraylist

Accessing an ArrayList
The ArrayList class implements the IList interface. So, elements can be accessed using indexer, in
the same way as an array. Index starts from zero and increases by one for each subsequent element.

An explicit casting to the appropriate types is required, or use the var variable.

Example: Accessing Elements of ArrayList


var arlist = new ArrayList()
{
1,
"Bill",
300,
4.5f
};
//Access individual item using indexer
int firstElement = (int) arlist[0]; //returns 1
string secondElement = (string) arlist[1]; //returns "Bill"
//int secondElement = (int) arlist[1]; //Error: cannot cover string to int

//using var keyword without explicit casting


var firstElement = arlist[0]; //returns 1
var secondElement = arlist[1]; //returns "Bill"
//var fifthElement = arlist[5]; //Error: Index out of range

//update elements
arlist[0] = "Steve";
arlist[1] = 100;
//arlist[5] = 500; //Error: Index out of range

Iterate an ArrayList
The ArrayList implements the ICollection interface that supports iteration of the collection types.
So, use the foreach and the for loop to iterate an ArrayList. The Count property of an ArrayList
returns the total number of elements in an ArrayList.

Example: Iterate ArrayList


ArrayList arlist = new ArrayList()
{
1,
"Bill",
300,
4.5F
};

foreach (var item in arlist)


Console.Write(item + ", "); //output: 1, Bill, 300, 4.5,

for(int i = 0 ; i < arlist.Count; i++)


Console.Write(arlist[i] + ", "); //output: 1, Bill, 300, 4.5,

Insert Elements in ArrayList


Use the Insert() method to insert an element at the specified index into an ArrayList.

Signature: void Insert(int index, Object value)

Example: Insert Element in ArrayList


ArrayList arlist = new ArrayList()
{
1,
"Bill",
300,
4.5f
};

arlist.Insert(1, "Second Item");

foreach (var val in arlist)


Console.WriteLine(val);

Use the InsertRange() method to insert a collection in an ArrayList at the specfied index.
Signature: Void InsertRange(int index, ICollection c)

Example: Insert Collection in ArrayList


ArrayList arlist1 = new ArrayList()
{
100, 200, 600
};

ArrayList arlist2 = new ArrayList()


{
300, 400, 500
};
arlist1.InsertRange(2, arlist2);

foreach(var item in arlist1)


Console.Write(item + ", "); //output: 100, 200, 300, 400, 500, 600,

Remove Elements from ArrayList


Use the Remove(), RemoveAt(), or RemoveRange methods to remove elements from an ArrayList.

Example: Remove Elements from ArrayList


ArrayList arList = new ArrayList()
{
1,
null,
"Bill",
300,
" ",
4.5f,
300,
};

arList.Remove(null); //Removes first occurance of null


arList.RemoveAt(4); //Removes element at index 4
arList.RemoveRange(0, 2);//Removes two elements starting from 1st item (0 index)

Check Element in ArrayList


Use the Contains() method to determine whether the specified element exists in the ArrayList or
not. It returns true if exists otherwise returns false.

Example: Check for Elements


ArrayList arList = new ArrayList()
{ 1,
"Bill",
300,
4.5f,
300
};

Console.WriteLine(arList.Contains(300)); // true
Console.WriteLine(arList.Contains("Bill")); // true
Console.WriteLine(arList.Contains(10)); // false
Console.WriteLine(arList.Contains("Steve")); // false
Note:
It is not recommended to use the ArrayList class due to performance issue. Instead, use
List<object> to store heterogeneous objects. To store data of same data type, use Generic List<T>.
ArrayList Properties
Properties Description
Capacity Gets or sets the number of elements that the ArrayList can contain.
Count Gets the number of elements actually contained in the ArrayList.
IsFixedSize Gets a value indicating whether the ArrayList has a fixed size.
IsReadOnly Gets a value indicating whether the ArrayList is read-only.
Item Gets or sets the element at the specified index.

ArrayList Methods
Methods Description
Add() method adds single elements at the end of ArrayList.
Add()/AddRange() AddRange() method adds all the elements from the specified collection
into ArrayList.
Insert() method insert a single elements at the specified index in
ArrayList.
Insert()/InsertRange()
InsertRange() method insert all the elements of the specified collection
starting from specified index in ArrayList.
Remove() method removes the specified element from the ArrayList.
Remove()/RemoveRange() RemoveRange() method removes a range of elements from the
ArrayList.
RemoveAt() Removes the element at the specified index from the ArrayList.
Sort() Sorts entire elements of the ArrayList.
Reverse() Reverses the order of the elements in the entire ArrayList.
Checks whether specified element exists in the ArrayList or not. Returns
Contains
true if exists otherwise false.
Clear Removes all the elements in ArrayList.
CopyTo Copies all the elements or range of elements to compitible Array.
Returns specified number of elements from specified index from
GetRange
ArrayList.
Search specified element and returns zero based index if found. Returns
IndexOf
-1 if element not found.
ToArray Returns compitible array from an ArrayList.

C# - List< >
The List<T> is a collection of strongly typed objects that can be accessed by index and having
methods for sorting, searching, and modifying list. It is the generic version of the ArrayList that
comes under System.Collections.Generic namespace.

List<T> Characteristics
• List<T> equivalent of the ArrayList, which implements IList<T>.
• It comes under System.Collections.Generic namespace.
• List<T> can contain elements of the specified type. It provides compile-time type checking
and doesn't perform boxing-unboxing because it is generic.
• Elements can be added using the Add(), AddRange() methods or collection-initializer syntax.
• Elements can be accessed by passing an index e.g. myList[0]. Indexes start from zero.
• List<T> performs faster and less error-prone than the ArrayList.

Creating a List
The List<T> is a generic collection, so you need to specify a type parameter for the type of data it
can store. The following example shows how to create list and add elements.

Example: Adding elements in List


List<int> primeNumbers = new List<int>();
primeNumbers.Add(2); // adding elements using add() method
primeNumbers.Add(3);
primeNumbers.Add(5);
primeNumbers.Add(7);

var cities = new List<string>();


cities.Add("New York");
cities.Add("London");
cities.Add("Mumbai");
cities.Add("Chicago");
cities.Add(null);// nulls are allowed for reference type list

//adding elements using collection-initializer syntax


var bigCities = new List<string>()
{
"New York",
"London",
"Mumbai",
"Chicago"
};

In the above example, List<int> primeNumbers = new List<int>(); creates a list of int type. In
the same way, cities and bigCities are string type list. You can then add elements in a list using
the Add() method or the collection-initializer syntax.

You can also add elements of the custom classes using the collection-initializer syntax. The
following adds objects of the Student class in the List<Student>.

Example: Add Custom Class Objects in List


var students = new List<Student>() {
new Student(){ Id = 1, Name="Bill"},
new Student(){ Id = 2, Name="Steve"},
new Student(){ Id = 3, Name="Ram"},
new Student(){ Id = 4, Name="Abdul"}
};

Adding an Array in a List


Use the AddRange() method to add all the elements from an array or another collection to List.

AddRange() signature: void AddRange(IEnumerable<T> collection)

Example: Add Arrays in List


string[] cities = new string[3]{ "Mumbai", "London", "New York" };

var popularCities = new List<string>();

// adding an array in a List


popularCities.AddRange(cities);

var favouriteCities = new List<string>();

// adding a List
favouriteCities.AddRange(popularCities);

Accessing a List
A list can be accessed by an index, a for/foreach loop, and using LINQ queries. Indexes of a list start
from zero. Pass an index in the square brackets to access individual list items, same as array. Use a
foreach or for loop to iterate a List<T> collection.

Example: Accessing List


List<int> numbers = new List<int>() { 1, 2, 5, 7, 8, 10 };
Console.WriteLine(numbers[0]); // prints 1
Console.WriteLine(numbers[1]); // prints 2
Console.WriteLine(numbers[2]); // prints 5
Console.WriteLine(numbers[3]); // prints 7

// using foreach LINQ method


numbers.ForEach(num => Console.WriteLine(num + ", "));//prints 1, 2, 5, 7, 8, 10,

// using for loop


for(int i = 0; i < numbers.Count; i++)
Console.WriteLine(numbers[i]);

Accessing a List using LINQ


The List<T> implements the IEnumerable interface. So, we can query a list using LINQ query
syntax or method syntax, as shown below.

Example: LINQ Query on List


var students = new List<Student>() {
new Student(){ Id = 1, Name="Bill"},
new Student(){ Id = 2, Name="Steve"},
new Student(){ Id = 3, Name="Ram"},
new Student(){ Id = 4, Name="Abdul"}
};

//get all students whose name is Bill


var result = from s in students
where s.Name == "Bill"
select s;

foreach(var student in result)


Console.WriteLine(student.Id + ", " + student.Name);
Insert Elements in List
Use the Insert() method inserts an element into the List<T> collection at the specified index.

Insert() signature:void Insert(int index, T item);

Example: Insert elements into List


var numbers = new List<int>(){ 10, 20, 30, 40 };

numbers.Insert(1, 11);// inserts 11 at 1st index: after 10.

foreach (var num in numbers)


Console.Write(num);

Remove Elements from List


Use the Remove() method to remove the first occurrence of the specified element in the List<T>
collection. Use the RemoveAt() method to remove an element from the specified index. If no
element at the specified index, then the ArgumentOutOfRangeException will be thrown.

Remove() signature: bool Remove(T item)

RemoveAt() signature: void RemoveAt(int index)

Example: Remove elements from List


var numbers = new List<int>(){ 10, 20, 30, 40, 10 };

numbers.Remove(10); // removes the first 10 from a list

numbers.RemoveAt(2); //removes the 3rd element (index starts from 0)

//numbers.RemoveAt(10); //throws ArgumentOutOfRangeException

foreach (var el in intList)


Console.Write(el); //prints 20 30

Check Elements in List


Use the Contains() method to determine whether an element is in the List<T> or not.

Example: Contains()
var numbers = new List<int>(){ 10, 20, 30, 40 };
numbers.Contains(10); // returns true
numbers.Contains(11); // returns false
numbers.Contains(20); // returns true

List<T> Class Properties and Methods


The following table lists the important properties and methods of List<T> class:
Property Usage
Items Gets or sets the element at the specified index
Count Returns the total number of elements exists in the List<T>
Method Usage
Add Adds an element at the end of a List<T>.
AddRange Adds elements of the specified collection at the end of a List<T>.
BinarySearch Search the element and returns an index of the element.
Clear Removes all the elements from a List<T>.
Contains Checks whether the specified element exists or not in a List<T>.
Find Finds the first element based on the specified predicate function.
Foreach Iterates through a List<T>.
Insert Inserts an element at the specified index in a List<T>.
InsertRange Inserts elements of another collection at the specified index.
Remove Removes the first occurrence of the specified element.
RemoveAt Removes the element at the specified index.
RemoveRange Removes all the elements that match the supplied predicate function.
Sort Sorts all the elements.
TrimExcess Sets the capacity to the actual number of elements.
Determines whether every element in the List<T> matches the conditions defined by
TrueForAll
the specified predicate.

C# - S rtedList< Key, Value>


The SortedList<TKey, TValue>, and SortedList are collection classes that can store key-value
pairs that are sorted by the keys based on the associated IComparer implementation. For example, if
the keys are of primitive types, then sorted in ascending order of keys.

C# supports generic and non-generic SortedList. It is recommended to use generic


SortedList<TKey, TValue> because it performs faster and less error-prone than the non-generic
SortedList.

SortedList Characteristics
• SortedList<TKey, TValue> is an array of key-value pairs sorted by keys.
• Sorts elements as soon as they are added. Sorts primitive type keys in ascending order and
object keys based on IComparer<T>.
• Comes under System.Collection.Generic namespace.
• A key must be unique and cannot be null.
• A value can be null or duplicate.
• A value can be accessed by passing associated key in the indexer mySortedList[key]
• Contains elements of type KeyValuePair<TKey, TValue>
• It uses less memory than SortedDictionary<TKey,TValue>.
• It is faster in the retrieval of data once sorted, whereas SortedDictionary<TKey, TValue>
is faster in insertion and removing key-value pairs.
Creating a SortedList
The following example demonstrates how to create a generic SortedList<TKey, TValue>, and add
key-value pairs in it.

Example: Create a SortedList and Add Elements


//SortedList of int keys, string values
SortedList<int, string> numberNames = new SortedList<int, string>();
numberNames.Add(3, "Three");
numberNames.Add(1, "One");
numberNames.Add(2, "Two");
numberNames.Add(4, null);
numberNames.Add(10, "Ten");
numberNames.Add(5, "Five");

//The following will throw exceptions


//numberNames.Add("Three", 3); //Compile-time error: key must be int type
//numberNames.Add(1, "One"); //Run-time exception: duplicate key
//numberNames.Add(null, "Five");//Run-time exception: key cannot be null

In the above example, a generic SortedList<TKey, TValue> object is created by specifying the
type of keys and values it is going to store. The SortedList<int, string> will store keys of int
type and values of string type.

The Add() method is used to add a single key-value pair in a SortedList. Keys cannot be null or
duplicate. If found, it will throw a run-time exception. Values can be duplicate and null if the type is
nullable.

Use the collection-initializer syntax to initialize a SortedList with multiple key-value pairs at the
time of instantiating, as shown below.

//Creating a SortedList of string keys, string values


//using collection-initializer syntax
SortedList<string,string> cities = new SortedList<string,string>()
{
{"London", "UK"},
{"New York", "USA"},
{ "Mumbai", "India"},
{"Johannesburg", "South Africa"}
};

The SortedList rearranges key-value pairs in the ascending order of keys as soon as a key-value
pair added. The following example displays all the keys and values using foreach loop.

Example: SortedList Elements Default Sorting Order


SortedList<int,string> numberNames = new SortedList<int,string>()
{
{3, "Three"},
{5, "Five"},
{1, "One"}
};

Console.WriteLine("---Initial key-values--");

foreach(KeyValuePair<int, string> kvp in numberNames)


Console.WriteLine("key: {0}, value: {1}", kvp.Key , kvp.Value );

numberNames.Add(6, "Six");
numberNames.Add(2, "Two");
numberNames.Add(4, "Four");

Console.WriteLine("---After adding new key-values--");

foreach(var kvp in numberNames)


Console.WriteLine("key: {0}, value: {1}", kvp.Key , kvp.Value );
Output:
---Initial key-values--
key: 1, value: One
key: 3, value: Three
key: 5, value: Five
---After adding new key-values--
key: 1, value: One
key: 2, value: Two
key: 3, value: Three
key: 4, value: Four
key: 5, value: Five
key: 6, value: Six

Accessing SortedList
Specify a key in the indexer sortedList[key], to get or set a value in the SortedList.

Example: Access SortedList Values


SortedList<int,string> numberNames = new SortedList<int,string>()
{
{3, "Three"},
{1, "One"},
{2, "Two"}
};

Console.WriteLine(numberNames[1]); //output: One


Console.WriteLine(numberNames[2]); //output: Two
Console.WriteLine(numberNames[3]); //output: Three
//Console.WriteLine(numberNames[10]); //run-time KeyNotFoundException

numberNames[2] = "TWO"; //updates value


numberNames[4] = "Four"; //adds a new key-value if a key does not exists

Above, numberNames[10] will throw a KeyNotFoundException because specified key 10 does not
exist in a sortedlist. To prevent this exception, use ContainsKey() or TryGetValue() methods, as
shown below.

Example: ContainsKey() and TryGetValue()


SortedList<int, string> numberNames = new SortedList<int,string>()
{
{3, "Three"},
{1, "One"},
{2, "Two"}
};
if(numberNames.ContainsKey(4)){
numberNames[4] = "four";
}

int result;
if(numberNames.TryGetValue(4, out result))
Console.WriteLine("Key: {0}, Value: {1}", 4, result);
Output:
Key:4, Value: Four

Use Keys and Values properties if you want to iterate a SortedList using a for loop.

Example: Iterate SortedList using For Loop


SortedList<int, string> numberNames = new SortedList<int,string>()
{
{3, "Three"},
{1, "One"},
{2, "Two"}
};
for (int i = 0; i < numberNames.Count; i++)
{
Console.WriteLine("key: {0}, value: {1}", numberNames.Keys[i],
numberNames.Values[i]);
}
Output:
key: 1, value: One
key: 2, value: Two
key: 3, value: Three

Remove Elements from SortedList


Use the Remove(key) and RemoveAt(index) methods to remove key-value pairs from a
SortedList.

Example: Remove Elements


SortedList<int,string> numberNames = new SortedList<int,string>()
{
{3, "Three"},
{1, "One"},
{2, "Two"},
{5, "Five"},
{4, "Four"}
};

numberNames.Remove(1);//removes key 1 pair


numberNames.Remove(10);//removes key 1 pair, no error if not exists

numberNames.RemoveAt(0);//removes key-value pair from index 0


//numberNames.RemoveAt(10);//run-time exception: ArgumentOutOfRangeException

foreach(var kvp in numberNames)


Console.WriteLine("key: {0}, value: {1}", kvp.Key , kvp.Value );
Output:
key: 3, value: Three
key: 4, value: Four
key: 5, value: Five

You might also like