Chapter 3- Data Structures in C#
Chapter 3- Data Structures in C#
ARRAY
STRING
STRUCTURE
LIST
DICTIONARY
3
ARRAY … (1)
An array stores a fixed-size collection of elements of the same type stored at sequential memory locations.
Length of the array specifies the number of elements present in the array.
The variables in the array are ordered and each has an index beginning from 0.
Default values of numeric array and reference type elements are set to be respectively zero and null.
4
ARRAY … (2)
C# ARRAYS
SINGLE MULTI-
JAGGED
DIMENSIONAL DIMENSIONAL
ARRAYS OF ARRAY
5
ARRAY … SINGLE DIMENSIONAL ARRAY
6
ARRAY … MULTI DIMENSIONAL ARRAY
C# ARRAY OPERATIONS USING SYSTEM.LINQ … (1)
7
In C#, we have the System.Linq namespace that provides different methods to perform various
BinarySearch() used to search a value in a sorted one dimensional array Array.BinarySearch(arrName, element);
Array.Find(arrName,
FindAll() Retrieves all the elements that match the conditions.
e => e.StartsWith("S“);
Array arr =
CreateInstance() Initializes a new instance of the Array class.
Array.CreateInstance(typeof(String), 6);
For declaring the strings we will continue using the keyword string, which is an alias in C# of the
Declared the variable greeting of type string whose content is the text phrase "Hello, C#".
H E L L O , C #
The internal representation of the class is However, there are some disadvantages too:
quite simple – an array of characters. o Filling in the array happens character by character, not at once.
We can avoid the usage of the class by o We should know the length of the text in order to be aware
declaring a variable of type char[] and fill in whether it will fit into the already allocated space for the array.
Strings are very similar to the char arrays (char[]), but unlike them, they cannot be modified.
Like the arrays, they have properties such as Length, which returns the length of the string and allows access by
index.
Access to the character of a certain position in a string is done with the operator [] (indexer), but it is allowed only
ch = str[50]; // IndexOutOfRangeException
15
STRING … (4)
}
16
STRING … (5)
Strings Escaping
As we already know, if we want to use quotes into the string content, we must put a slash before them to
identify that we consider the quotes character itself and not using the quotation marks for ending the string:
They are added in the variable by placing them after the escaping character backslash (\).
In this way the compiler recognizes that the quotes are not used to start or end a string, but are a part of the data.
# Method Example
STR1 HEAP
str1 && str2 are variable name
The string class provides a wide range of methods and properties that you can use to manipulate and work
with strings. Some of the commonly used methods and properties of the string class include:
o Trim: removes any leading or trailing whitespace characters from the string
o Split: splits the string into an array of substrings based on a specified delimiter character or substring
o Compare: This method returns an int value, if string1 is smaller than string2 then it returns -1, if
string1 is larger than string2 then it returns 1, if both strings are equal then it returns 0.
o IsNullOrWhiteSpace: Returns true if string contains blank, null or any whitespace characters.
21
STRING … (10)
COPY
CLONE
-----------------------------------------------------
string str2 = string.Copy(str1);
STR1 HEAP
HELLO WORLD
STR1 HEAP
#12e2023
COPY
CLONE
You might want to track the following attributes about each book
struct Books
{
public string title;
public string subject;
};
28
STRUCTURE … (3)
Write a program that allow to register students with the following information
EXPECTED OUTPUT
# Name StudID Gender Department
data type then you can create a List that will store only
To work with the C# List, you need to add the following namespace at the beginning
your code:
o using System.Collections.Generic;
C# List class provides several methods for manipulating the items it contains.
35
LIST … (4)
The number of elements in a list is stored Capacity property used to limit number of elements in a list.
in the Count property. In the example code, the Capacity of citiesList is 4 by default
Count() Capacity()
36
LIST … (5)
Remove()
List<string> citiesList = new List<string>();
citiesList.Add(“Addis Ababa");
Elements of a list can be removed
citiesList.Add(“Adama");
with the Remove() method. The
citiesList.Add(“Jimma");
method returns true if the item is bool res = citiesList.Remove(“Addis Ababa"); //True
successfully removed; otherwise, bool res = citiesList.Remove(“Mekele"); //False
Clear()
Contains()
Range-related Methods
string[] african = new string[] { "Cairo", "Johannesburg" };
string[] asian = new string[] { "Delhi", "Seoul" };
Unlike elements in a C# array, multiple
List<string> citiesList = new List<string>();
elements of a C# list can be accessed,
// Add two cities to the list
added, or removed simultaneously.
citiesList.AddRange(african);
A group of multiple, sequential
// List: "Cairo", "Johannesburg"
elements within a list is called a range.
// Add two cities at index=0
Some common range-related methods
citiesList.InsertRange(0, asian);
are: AddRange(); InsertRange(); // List: "Delhi", "Seoul", "Cairo", "Johannesburg"
// Remove 2 elements starts from index=1
RemoveRange()
citiesList.RemoveRange(1, 2);
struct Customer
{
public string Name;
public string City;
LINQ is a set of language and framework features for writing queries on collection types.
VAR
var findCustomer = from cust in
Since the type of an executed LINQ query’s
customers where cust.City == “Aweday"
result is not always known, it is common to
select cust;
store the result in an implicitly typed variable
//Output
using the keyword var. Amir, Aweday
Semira, Aweday
42
LIST … LINQ (2)
// Method syntax
var findCustomer = customers.Where(cust => cust.City ==
METHOD & QUERY SYNTAX
“Aweday");
In C#, LINQ queries can be written
Method syntax resembles most var findCustomer = from cust in customers where cust.City
== “Aweday" select cust;
other C# method calls, while query
WHERE
FROM
string[] names = { “Amir", “Ujulu", “Selam", “Chala" };
In LINQ queries, the from operator
var query = from n in names where n.Contains("a")
declares a range variable that is used
select n;
to traverse the sequence. It is only used
In LINQ queries, the Select var cap = from n in names select n.ToUpper();
// Method syntax
operator determines what is
var cap = names.Select(t => t.ToUpper());
returned for each element in the
foreach (var name in cap)
resulting query. It can be used in
{
Console.WriteLine(name);
both method and query syntax.
}
// Result: AMIR, UJULU, SELAM, CHALA
46
CLASS WORK
Write a program that allow to register students with the following information
EXPECTED OUTPUT
# Name StudID Gender Department
2 Ujulu CEP002 M CS
FEATURE: Allow the user to search by Gender and Department Using LINQ
47
DICTIONARY … (1)
Here are some examples of when you might use a dictionary in C#:
using System.Collections.Generic;
// Create a dictionary SYNTAX
Dictionary<TKey, TValue> DictName = new Dictionary<TKey, TValue> ();
// Where TKey is the type of the keys, and TValue is the type of the values.
// create a dictionary
2
Dictionary<int, string> Contacts = new Dictionary<int, string>();
ACCESS ELEMENTS
// add items to dictionary
We can access the elements
Contacts.Add(920, "Abebe");
inside the dictionary using it's Contacts.Add(910, "Amir");
keys. Contacts.Add(909, "Ujulu");
// iterate through the car dictionary
In C#, we can also loop through
foreach (KeyValuePair<int, string> contact in Contacts)
each element of the dictionary
{
using a foreach loop. Console.WriteLine(“Key: {0}, Value: {1}", contact.Key, contact.Value);
}
53
DICTIONARY … BASIC OPERATIONS (1)
NOTE:
APPLY STRUCTURE, LIST & DICTIONARY DATA STRUCTURES AND CONSIDER HCI CONCEPTS
TEACHING YOU IS GOOD LUCK