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

C# Module 2

Uploaded by

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

C# Module 2

Uploaded by

amogh.patadi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

MODULE-2

Data Structures and Data Manipulation in C#


ARRAYS
• In C#, all arrays are dynamically allocated.
• A C# array variable can also be declared like other variables with []
after the data type.
• The variables in the array are ordered and each has an index beginning
from 0.
• C# array is an object of base type System.Array.
• Once created, the size of an array cannot be changed.
.
Example 1: Integer Array
class Program
{
static void Main(string[] args)
{
// Creating an integer array with 5 elements
int[] numbers = { 10, 20, 30, 40, 50 };
// Accessing and printing array elements
Console.WriteLine("First element: " + numbers[0]);
// Output: First element: 10
}
}
Example 2: String Array
class Program
{
static void Main(string[] args)
{
// Creating a string array with 3 elements and initializing it
string[] colors = { "red", "green", "blue" };
// Accessing and printing the second element
Console.WriteLine("Second element: " + colors[1]); // Output:
Second element: green
}
}
Collection
• Collection is a group of homogenous and heterogenous data types.
• Collections in C# are data structures used to store and manipulate groups
of related objects.
• There are several types of collections in C# provided by the .NET
Framework, each with its own characteristics and use cases.
• Collections include : Arrays, Lists , Dictionaries, Sets, Queues, Stack,
Hashtable etc.
LISTS
• In C#, List is a generic collection which is used to store the elements
or objects in the form of a list.
• It is defined under System.Collection.Generic namespace.
• Lists are dynamic arrays, allowing for resizing and manipulation of
elements.

//Creating List using List class


List<int> numbersList = new List<int>();
//Adding elements using the Collection initializers
List<int> numbersList = new List<int>();{0,1,2,3,4,5,6,7,8,9};
LISTS
class Program
{
static void Main(string[] args)
{
// Creating a list of integers and adding elements
List<int> numbers = new List<int> { 10, 20, 30, 40, 50 };

// Accessing and printing list elements


Console.WriteLine("First element: " + numbers[0]);
// Output: First element: 10
Console.WriteLine("Second element: " + numbers[1]);
// Output: Second element: 20
}
}
DICTIONARIES
• In C#, Dictionary is a generic collection which is generally used to
store key/value pairs.
• Dictionary is defined under System.Collections.Generic namespace.
• In Dictionary, you can only store same types of elements.
• In Dictionary, the key cannot be null, but value can be null.
• In Dictionary, key must be unique. Duplicate keys are not allowed if
you try to use duplicate key then compiler will throw an exception.
• The advantage of Dictionary is, it is generic type.
• It is dynamic in nature means the size of the dictionary is grows
according to the need
DICTIONARIES
class Program
{
static void Main(string[] args)
{
// Creating a dictionary with string keys and int values
Dictionary<string, int> ages = new Dictionary<string, int>();
// Adding key-value pairs
ages["Alice"] = 30;
ages["Bob"] = 25;
// Accessing value by key
Console.WriteLine("Alice's age: " + ages["Alice"]); // Output: Alice's age: 30
}
}
SETS -HASHSET
• Sets store unique elements and provide methods for set operations like
union, intersection, and difference.
• In C#, HashSet is an unordered collection of unique elements.
• It supports the implementation of sets and uses the hash table for
storage.
• This collection is of the generic type collection and it is defined
under System.Collections.Generic namespace.
• It is generally used when we want to prevent duplicate elements from
being placed in the collection.
• The performance of the HashSet is much better in comparison to the
list.
HASHSET
• In HashSet, the order of the element is not defined. You cannot sort the
elements of HashSet.
• In HashSet, the elements must be unique.
• In HashSet, duplicate elements are not allowed.
• It provides many mathematical set operations, such as intersection,
union, and difference.
• The capacity of a HashSet is the number of elements it can hold.
• A HashSet is a dynamic collection means the size of the HashSet is
automatically increased when the new elements are added.
• In HashSet, you can only store the same type of elements.
HASHSET
class Program
{
static void Main(string[] args)
{
// Creating a HashSet of integers and adding elements
HashSet<int> numbers = new HashSet<int> { 10, 20, 30 };
// Checking if an element exists
Console.WriteLine("Does 30 exist in the set? " + numbers.Contains(30));
// Output: Does 30 exist in the set? True
// Printing all elements
Console.WriteLine("All elements: " + string.Join(", ", numbers));
// Output: All elements: 10, 20, 30
}
}
SORTED SET
• In C#, SortedSet is a collection of objects in sorted order.
• It is of the generic type collection and defined
under System.Collections.Generic namespace.
• It also provides many mathematical set operations, such as
intersection, union, and difference.
• It is a dynamic collection means the size of the SortedSet is
automatically increased when the new elements are added.
• In SortedSet, the elements must be unique and the order of the element
is ascending.
• The user can only store the same type of elements in sorted set.
SORTED SET
class Program
{
static void Main(string[] args)
{
// Creating a SortedSet of integers
SortedSet<int> numbers = new SortedSet<int> { 30, 10, 20 };
// Adding a new element
numbers.Add(25);
// Removing an element
numbers.Remove(10);
// Printing all elements
Console.WriteLine("All elements: " + string.Join(", ", numbers));
// Output: All elements: 20, 25, 30
}
}
QUEUE
• A Queue is used to represent a first-in, first out(FIFO) collection
of objects. It is used when you need first-in, first-out access of
items.
• It is the non-generic type of collection which is defined in
System.Collections namespace.
• It is used to create a dynamic collection which grows, according
to the need of your program.
• In Queue, you can store elements of the same type and of the
different types.
QUEUE
class Program
{
static void Main(string[] args)
{
// Creating a Queue of integers
Queue<int> queue = new Queue<int>();
// Enqueuing elements into the queue
queue.Enqueue(10);
queue.Enqueue(20);
// Dequeuing an element from the queue
int dequeuedItem = queue.Dequeue(); // Dequeues the first element (10)
// Printing the dequeued item
Console.WriteLine("Dequeued item: " + dequeuedItem);
// Output: Dequeued item: 10
}
}
LINKED LIST
• In C#, LinkedList is the generic type of collection which is defined
in System.Collections.Generic namespace.
• A LinkedList is a linear data structure which stores element in the
non-contiguous location.
• A Singly LinkedList consists of nodes where each node contains a data field
and a reference(link) to the next node in the list.
• In doubly linked list, Each node points forward to the Next node and
backward to the Previous node.
• If the LinkedList is empty, the First and Last properties contain null.
• It is allowed to store duplicate elements but of the same type in linked list.
LINKED LIST
class Program
{
static void Main(string[] args)
{
// Creating a LinkedList of integers
LinkedList<int> linkedList = new LinkedList<int>();
// Adding elements to the linked list
linkedList.AddLast(10);
linkedList.AddLast(20);
// Printing all elements of the linked list
foreach (int item in linkedList)
{
Console.WriteLine(item);
}
}
}
Working With Strings
• In C#, string is a sequence of Unicode characters or array of
characters.
• A string is represented by class System.String.

CREATING STRINGS :

Example :
string str1 = "Hello, world!";
string str2 = new string(‘XYZ’, 3); // Output “XYZXYZXYZ"
Working With Strings
STRING CONCATENATION :

string firstName = "John";


string lastName = “Paul";
string fullName = firstName + " " + lastName; // "John Paul"
string concatFullName = string.Concat(firstName, " ", lastName); // "John Paul"
Working With Strings
STRING INTERPOLATION :

string interpolatedFullName = $"{firstName} {lastName}"; // "John Paul"

ACCESSING CHARACTERS :

char firstChar = fullName[0]; // 'J'


Working With Strings
STRING LENGTH :

int length = fullName.Length; // Output : 10 (length of name : “John Paul”)

SUBSTRINGS :

string substring = fullName.Substring(0, 4); // Output : "John"


Working With Strings
SPLITTING STRINGS

string sentence = "The quick brown fox";


string[] words = sentence.Split(' '); // {"The", "quick", "brown", "fox"}

JOINING STRINGS

string[] words = {"The", "quick", "brown", "fox"};


string sentence = string.Join(" ", words); // "The quick brown fox"
Working With Strings
CHANGING CASE

string uppercase = fullName.ToUpper(); // "JOHN PAUL"


string lowercase = fullName.ToLower(); // "john paul"

CHECKING FOR SUBSTRINGS

bool containsFox = sentence.Contains("fox"); // true


Working With Strings

COMPARING STRINGS :

string author1 = "Mahesh Chand";


string author2 = "Praveen Kumar";
// Compare strings using String.Equals
if (String.Equals(author1, author2))
Console.WriteLine($"{author1} and {author2} have same value.");
else
Console.WriteLine($"{author1} and {author2} are different.");
//Mahesh Chand and Praveen Kumar are different.
STRING TYPE
STRING LITERALS

string str = "Hello, world!";

string newline = "First line\nSecond line";


string path = "C:\\Windows\\System32";
STRING LITERALS

string filePath = @"C:\Windows\System32\";

string name = "John";


string greeting = $"Hello, {name}!";

string fullName = firstName + " " + lastName;


CHAR LITERALS

char grade = 'A';

char euroSymbol = '€';

char newline = '\n';


char tab = '\t';
CHAR LITERALS

char c = (char)65; // c = 'A'


int asciiValue = (int)'A'; // asciiValue = 65
FORMATTING DATA FOR OUTPUT
• Formatting data for output in C# involves using various formatting techniques to
present data in a structured and readable way.
• Standard Numeric Format Specifiers :
They can be used to convert numbers to strings in various formats. There are various
formats in which a number can be converted; the list of format types is:
✔ Number ( "N") Format Specifier
✔ Decimal ("D") Format Specifier
✔ Exponential ("E") Format Specifier
✔ Percent ("P") Format Specifier
✔ Fixed-Point ("F") Format Specifier
Standard Numeric Format Specifiers
• Number ( "N") Format Specifier
This Format Specifier can be used to convert a number into a string of the form
"-d,ddd,ddd.ddd....." where d represents any number between 0 to 9. The negative
sign represents a negative number and "." denotes the decimal point in the number
and "," denotes the group separator.
Example:
int number = 12345;
Console.WriteLine(number.ToString("N")); // Output=12,345.00
Standard Numeric Format Specifiers
• Decimal ("D") Format Specifier
The "D" (or decimal) format specifier works for integer type. It converts a number to a
string of decimal digits (0-9).
Example :
Class Demo
{
Static void Main()
{
int val;
val=877;
Console.WriteLine(val.ToString(“D”));//Output :877
Console.WriteLine(val.ToString(“D4”));//Output:0877
Console.WriteLine(val.ToString(“D8”));//Output:00000877
}
}
Standard Numeric Format Specifiers
• Exponential ("E") Format Specifier
The exponential ("E") format specifier is used to represent a number in scientific
notation. It converts a number to a string of the form "-d.ddd…E+ddd" or
"-d.ddd…e+ddd", where each "d" indicates a digit (0-9). The string starts with a
minus sign if the number is negative. Exactly one digit always precedes the decimal
point.
Example :
double number = 123456789.0123456789;
// Using exponential format specifier
Console.WriteLine(number.ToString("E"));
// Output: 1.234568E+008
// Specifying precision
Console.WriteLine(number.ToString("E3"));
// Output: 1.235E+008 (with 3 decimal places)
Standard Numeric Format Specifiers
• Percent ("P") Format Specifier
The percent ("P") format specifier is used to multiply a number by 100.It converts
the number into a string representing a % (percentage).
Example :
class Demo {
static void Main() {
double val = .975746;
Console.WriteLine(val.ToString("P"));//Output=97.57%
Console.WriteLine(val.ToString("P1"));// Output= 97.6%
Console.WriteLine(val.ToString("P4"));// Output= 97.5746
}
}
Standard Numeric Format Specifiers
• Fixed-Point ("F") Format Specifier
The fixed-point ("F") format specifier converts a number to a string of the form
"-ddd.ddd…" where each "d" indicates a digit (0-9). The string starts with a minus sign if the
number is negative.
Example :
int val;
val = 38788;
Console.WriteLine(val.ToString("F")); // Output :38788.00
val = -344;
Console.WriteLine(val.ToString("F3"));//Output:-344.000
val = 5656;
Console.WriteLine(val.ToString("F5"));//Output:5656.00000
}
}
Custom Numeric Format Specifiers
• A custom numeric format string consists of one or more custom
numeric specifiers to define how to format numeric data.
• The “0” custom specifier :
It represents a Zero placeholder. It replaces the zero with the corresponding digit if one is present;
otherwise zero appears in the result string.

Example :
double value;
value = 123;
Console.WriteLine(value.ToString("00000"));// Displays 00123
value = 1.2;
Console.WriteLine(value.ToString("0.00“));// Displays 1.20
Console.WriteLine(value.ToString("00.00“));// Displays 01.20
Custom Numeric Format Specifiers
• The “#” custom specifier :
It serves as a digit-placeholder symbol. If the value that is being formatted has a digit
in the position where the "#" symbol appears in the format string, that digit is copied
to the result string. Otherwise, nothing is stored in that position in the result string.

Example:
value = 123456;
Console.WriteLine(value.ToString("[##-##-##]"));
//Displays 12-34-56
Console.WriteLine(value.ToString("(###) ###-####"));
//Displays (123) 456-7890
Custom Numeric Format Specifiers
• The "." custom specifier
It is used to represent the decimal point in a numeric format string. It's
used to specify the location of the decimal point in the formatted output.

Example:
value = 1.2;
Console.WriteLine(value.ToString("0.00”));//Displays 1.20
Console.WriteLine(value.ToString("00.00”));//Displays 01.20
Custom Numeric Format Specifiers
• The "," custom specifier
The "," custom specifier in C# is used as a thousands separator when
formatting numbers. It's commonly used to improve readability by
inserting commas between groups of three digits.
Example :
int number = 1234567;
Console.WriteLine(number.ToString("#,###"));
// Output: 1,234,567
double money = 1234567.89;
Console.WriteLine(money.ToString("#,##0.00"));
// Output: 1,234,567.89
Custom Numeric Format Specifiers
• The "%" custom specifier
A percent sign (%) in a format string causes a number to be
multiplied by 100 before it is formatted. The localized percent
symbol is inserted in the number at the location where the %
appears in the format string.

Example:
double number = 0.75;
Console.WriteLine(number.ToString("0%")); // Output: 75%
Custom Numeric Format Specifiers
• The “0.00” custom specifier: It Formats the number to have two
decimal places, even if they're zeroes.
Example:
double number = 12.3;
Console.WriteLine(number.ToString("0.00")); // Output: 12.30

• The “0.##” custom specifier: It Formats the number with a variable


number of decimal places, but at least one.
Example:
double number1 = 12.345;
double number2 = 12.3;
Console.WriteLine(number1.ToString("0.##")); // Output: 12.35
Console.WriteLine(number2.ToString("0.##")); // Output: 12.3
DATES AND TIMES
In C#, dates and times are represented by the DateTime structure, which is part of the
System namespace.

Example:
DateTime now = DateTime.Now; // Current date and time in local time zone
DateTime utcNow = DateTime.UtcNow; // Current date and time in UTC
DATES AND TIMES

Example:

DateTime now = DateTime.Now;


string formattedDate = now.ToString("MM/dd/yyyy"); // Output: "04/29/2024"
string formattedTime = now.ToString("HH:mm:ss"); // Output: "12:30:00"
string formattedDateTime = now.ToString("MM/dd/yyyy HH:mm:ss");
// Output: "04/29/2024 12:30:00"
DATES AND TIMES

Example:
string dateString = "2024-04-29";
DateTime parsedDate = DateTime.Parse(dateString); // Parses the string into a DateTime

Console.WriteLine(parsedDate); // Output: 4/29/2024 12:00:00 AM

The output format might vary depending on your system's default date and time
format settings. In this case, it's in the format of MM/dd/yyyy hh:mm:ss.
DATES AND TIMES

Example:
DateTime now = DateTime.Now; //Output = 4/29/2024 1:30:00PM
DateTime tomorrow = now.AddDays(1); // Adds one day, Output=4/30/2024 1:30:00PM
DateTime nextMonth = now.AddMonths(1); // Adds one month
//Output = 5/29/2024 1:30:00PM
TimeSpan difference = nextMonth - now; // Calculates the difference between two dates
//Output=30.00:00:00
DATES AND TIMES

Example:
TimeSpan interval = TimeSpan.FromMinutes(30); // Represents 30 minutes
DateTime futureTime = DateTime.Now.Add(interval); // Adds 30 minutes to current
time
Console.WriteLine("Current Date and Time: " + DateTime.Now);
//Output= 4/29/2024 2:00:00PM
Console.WriteLine("Future Time after 30 minutes: " + futureTime);
///Output= 4/29/2024 2:30:00PM
DATES AND TIMES

Example:
DateTime utcTime = DateTime.UtcNow;
DateTime localTime = utcTime.ToLocalTime();
// Convert UTC time to local time
DateTime anotherTimeZone = utcTime.ToLocalTime().AddHours(2);
// Convert to another time zone

Output : UTC Time: 4/29/2024 2:00:00 PM


Local Time: 4/29/2024 7:00:00 AM
Time in Another Time Zone (+2 hours): 4/29/2024 9:00:00 AM
Date and Time Formatting Using Standard Specifiers
Date and Time Formatting Using Standard Specifiers
Date and Time Formatting Using Standard Specifiers
Example:
DateTime now = DateTime.Now;
Console.WriteLine(now.ToString("d")); // Output: 4/29/2024
Console.WriteLine(now.ToString("D")); // Output: Monday, April 29, 2024
Console.WriteLine(now.ToString("f")); // Output: Monday, April 29, 2024 1:30 PM
Console.WriteLine(now.ToString("F")); // Output: Monday, April 29, 2024 1:30:00 PM
Console.WriteLine(now.ToString("g")); // Output: 4/29/2024 1:30 PM
Console.WriteLine(now.ToString("G")); // Output: 4/29/2024 1:30:00 PM
Console.WriteLine(now.ToString("t")); // Output: 1:30 PM
Console.WriteLine(now.ToString("T")); // Output: 1:30:00 PM
Console.WriteLine(now.ToString("y")); // Output: April, 2024
Console.WriteLine(now.ToString("o")); // Output: 2024-04-29T13:30:00.0000000
Date and Time Formatting Using Custom Specifiers
Date and Time Formatting Using Custom Specifiers
Date and Time Formatting Using Custom Specifiers

Example:
DateTime now = DateTime.Now;
Console.WriteLine(now.ToString("dd/MM/yyyy")); // Output: 29/04/2024
Console.WriteLine(now.ToString("ddd, MMM dd")); // Output: Mon, Apr 29
Console.WriteLine(now.ToString("yyyy-MM-dd")); // Output: 2024-04-29
Console.WriteLine(now.ToString("HH:mm:ss")); // Output: 13:30:00
Console.WriteLine(now.ToString("hh:mm:ss tt")); // Output: 01:30:00 PM
Converting Strings To Other Types

string strInt = "123";


int intValue = int.Parse(strInt);
Console.WriteLine(intValue); // Output: 123

string strDouble = "3.14";


double doubleValue = double.Parse(strDouble);
Console.WriteLine(doubleValue); // Output: 3.14
Converting Strings To Other Types

string strDecimal = "123.45";


decimal decimalValue = decimal.Parse(strDecimal);
Console.WriteLine(decimalValue); // Output: 123.45

string strBool = "True";


bool boolValue = bool.Parse(strBool);
Console.WriteLine(boolValue); // Output: True
Converting Strings To Other Types

string strDateTime = "2024-04-29";


DateTime dateTimeValue = DateTime.Parse(strDateTime);
Console.WriteLine(dateTimeValue); // Output: 4/29/2024 12:00:00 AM

6.
string strCustom = "42";
int customValue = (int)Convert.ChangeType(strCustom, typeof(int));
Console.WriteLine(customValue); // Output: 42

You might also like