OOP L12 Data Structures Lite
OOP L12 Data Structures Lite
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.
Array Representation
The following declares and adds values into an array in a single statement.
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.
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.
The following example add/update and retrieve array elements using indexes.
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.
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.
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.
UpdateArray(nums);
Let's understand the two-dimensional array. The following initializes the two-dimensional array.
// 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
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.
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.
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.
//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.
Use the InsertRange() method to insert a collection in an ArrayList at the specfied index.
Signature: Void InsertRange(int index, ICollection c)
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.
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>.
// 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: 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
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.
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.
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.
Console.WriteLine("---Initial key-values--");
numberNames.Add(6, "Six");
numberNames.Add(2, "Two");
numberNames.Add(4, "Four");
Accessing SortedList
Specify a key in the indexer sortedList[key], to get or set a value in the SortedList.
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.
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.