In this chapter we will become acquainted with some of the advanced capabilities of the C# language. To be more specific, we will pay attention on how to make queries to collections, using lambda expressions and LINQ, and how to add functionality to already created classes, using extension methods. We will get to know the anonymous types, describe their usage briefly and discuss lambda expressions and show in practice how most of the built-in lambda functions work. Afterwards, we will pay more attention to the LINQ syntax – we will learn what it is, how it works and what queries we can build with it. In the end, we will get to know the meaning of the keywords in LINQ, and demonstrate their capabilities with lots of examples.
5. Associative arrays are arrays indexed by keys
Not by the numbers 0, 1, 2, … (like traditional arrays)
Hold a set of pairs {key value}
Associative Arrays (Maps, Dictionaries)
Associative array
John Smith +1-555-8976
Lisa Smith +1-555-1234
Sam Doe +1-555-5030
key value
Traditional array
0 1 2 3 4
8 -3 12 408 33
key
value
5
7. 7
Traditional dictionaries
Uses a hash-table + list
Dictionary<K, V>
Keep the keys in their order of addition
Sorted dictionaries
Uses a balanced search tree
SortedDictionary<K, V>
Keep the keys sorted in their natural order
Dictionary<K, V> vs. SortedDictionary<K, V>
var dict =
new Dictionary<string, int>();
var sortedDict = new
SortedDictionary<int,int>();
8. Count – holds the number of key-value pairs
Keys – a set of unique keys
Values – a collection of all values
Basic operations: Add() / indexer [], Remove(), Clear()
8
var dict = new Dictionary<string, int>();
foreach(var key in dict.Keys)
Console.WriteLine(key);
Console.WriteLine(String.Join(", ", dict.Values));
Dictionaries: Functionality
9. Find key / value:
ContainsKey() – checks if a key is present in the dictionary
(fast operation)
ContainsValue() – checks if a value is present in the
dictionary (slow operation)
TryGetValue() – check if a key is present in the dictionary
and ouputs the value (or returns the default value)
9
Dictionaries: Functionality (2)
13. 13
Iterating through Dictionaries
Gosho 0881-456-987
Pesho 0881-123-987
Dictionary<string, string>
Alice +359-899-55-592
KeyValuePair<string, string> keyValuePair in
foreach loop
.Key .Value
Alice +359-899-55-592
Pesho 0881-123-987
0881-456-987Gosho
14. 14
Write a program to extract from given sequence of words all
elements that present in it odd number of times (case-insensitive)
Words are given in a single line, space separated
Print the result elements in lowercase, in their order of appearance
Problem: Odd Occurrences
Java C# PHP PHP JAVA C java java, c#, c
3 5 5 hi pi HO Hi 5 ho 3 hi pi 5, hi
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/174#1
a a A SQL xx a xx a A a XX c a, sql, xx, c
15. 15
Solution: Odd Occurrences
string input = Console.ReadLine().ToLower();
string[] words = input.Split(' ');
var counts = new Dictionary<string, int>();
foreach (var word in words)
if (counts.ContainsKey(word))
counts[word]++;
else counts[word] = 1;
var results = new List<string>();
foreach (var pair in counts)
// TODO: add pair.Key to results if pair.Value is odd
Console.WriteLine(string.Join(", ", results));
counts[word]
holds how many
times word occurs
in words
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/174#1
17. 17
Read a list of real numbers and print them in ascending order
along with their number of occurrences
Problem: Count Real Numbers
8 2.5 2.5 8 2.5
2.5 -> 3 times
8 -> 2 times
1.5 5 1.5 3
1.5 -> 2 times
3 -> 1 times
5 -> 1 times
-2 0.33 0.33 2
-2 -> 1 times
0.33 -> 2 times
2 -> 1 times
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/174#0
18. 18
Solution: Count Real Numbers
double[] nums = Console.ReadLine().Split(' ')
.Select(double.Parse).ToArray();
var counts = new SortedDictionary<double, int>();
foreach (var num in nums)
if (counts.ContainsKey(num))
counts[num]++;
else
counts[num] = 1;
foreach (var num in counts.Keys)
Console.WriteLine($"{num} -> {counts[num]}");
counts[num] will
hold how many times
num occurs in nums
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/174#0
21. 21
Min() – finds the smallest element in a collection
Max() – finds the largest element in a collection
Sum() – finds the sum of all elements in a collection
Average() – finds the average of all elements in a collection
Processing Sequences with LINQ
new List<int>() { 1, 2, 3, 4, -1, -5, 0, 50 }.Min() -5
new int[] { 1, 2, 3, 40, -1, -5, 0, 5 }.Max() 40
new long[] {1, 2, 3, 4, -1, -5, 0, 50}.Sum() 54
new int[] {1, 2, 3, 4, -1, -5, 0, 50}.Average() 6.75
22. 22
Write a program to read n integers and print their sum, min,
max and average values:
Problem: Sum, Min, Max, Average
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/174#2
5
12
20
-5
37
8
Sum = 72
Min = -5
Max = 37
Average = 14.4
4
50
20
25
40
Sum = 135
Min = 20
Max = 50
Average = 33.75
23. 23
Solution: Sum, Min, Max, Average
using System.Linq;
…
int n = int.Parse(Console.ReadLine());
int[] nums = new int[n];
for (int i = 0; i < n; i++)
nums[i] = int.Parse(Console.ReadLine());
Console.WriteLine("Sum = {0}", nums.Sum());
Console.WriteLine("Min = {0}", nums.Min());
// TODO: print also max and average values
Use System.Linq to enable LINQ
functions like .Max() and .Sum()
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/174#2
24. 24
Reading Collections on a Single Line
Using Select() to read collections:
var nums = Console.ReadLine()
.Split()
.Select(number => double.Parse(number));
// .Select(double.Parse); // short version
var nums = Console.ReadLine()
.Split()
.Select(int.Parse);
// .Select(number => int.Parse(number)); // long version
27. 27
Sorting Collections by Multiple Criteria
Using ThenBy() to sort collections by multiple criteria:
Dictionary<int, string> products =
new Dictionary<int, string>();
Dictionary<int, string> sortedDict = products
.OrderBy(pair => pair.Value)
.ThenBy(pair => pair.Key)
.ToDictionary(pair => pair.Key, pair => pair.Value);
28. 28
Take / Skip Elements from Collection
Using Take(), Skip():
var nums = new List<int>() { 10, 20, 30, 40, 50, 60}
.Take(3)
.ToArray();
// nums = [10, 20, 30]
var nums = new List<int>() { 10, 20, 30, 40, 50, 60}
.Skip(3).Take(2)
.ToArray();
// nums = [40, 30]
29. 29
Problem: Largest 3 Numbers
Read a list of real numbers and print largest 3 of them
10 30 15 20 50 5 50 30 20
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/174#3
20 30 30 20
0 -5 -1 -3 -2 0 -1 -2
30. 30
Solution: Largest 3 Numbers
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/174#3
List<int> nums = Console.ReadLine().Split()
.Select(int.Parse)
.ToList();
var sortedNums = nums.OrderByDescending(x => x);
var largest3Nums = sortedNums.Take(3);
Console.WriteLine(string.Join(" ", largest3Nums));
31. 31
A lambda expression is an anonymous function containing
expressions and statements
Lambda expressions
Use the lambda operator =>
Read as "goes to"
The left side specifies the input parameters
The right side holds the expression or statement
Lambda Expressions
var lambda = (a => a > 5);
32. 32
Lambda functions are inline methods (functions) that take input
parameters and return values:
Lambda Functions
x => x / 2 static int Func(int x) { return x / 2; }
static bool Func(int x) { return x != 0; }x => x != 0
() => 42 static int Func() { return 42; }
(x, y) => x+y static int Func(int x, int y)
{ return x+y; }
35. 35
Getting Unique Elements from Collection
Distinct() takes the unique elements from a collection:
int[] nums = { 1, 2, 2, 3, 4, 5, 6, -2, 2, 0,
15, 3, 1, 0, 6 };
nums = nums
.Distinct()
.ToArray();
// nums = [1, 2, 3, 4, 5, 6, -2, 0, 15]
36. 36
Read a text, extract its words, find all short words (less than 5
characters) and print them alphabetically, in lower case
Use the following separators: . , : ; ( ) [ ] " ' / ! ? (space)
Use case-insensitive matching; remove duplicated words
Problem: Short Words Sorted
In SoftUni you can study Java, C#, PHP and JavaScript.
JAVA and c# developers graduate in 2-3 years. Go in!
2-3, and, c#, can, go, in, java, php, you
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/174#4
37. 37
Solution: Short Words Sorted
char[] separators = new char[]
{'.',',',':',';','(',')','[',']','','"',''','/','!','?',' '};
string sentence = Console.ReadLine().ToLower();
string[] words = sentence.Split(separators);
var result = words
.Where(w => w != "")
// TODO: filter by word length < 5
.OrderBy(w => w).Distinct();
Console.WriteLine(string.Join(", ", result));
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/174#4
38. 38
Take Single Element from Collection
Using First(), Last() , Single():
int[] nums = { 1, 2, 3, 4, 5, 6 };
int firstNum = nums.First(x => x % 2 == 0); // 1
int lastNum = nums.Last(x => x % 2 == 1); // 6
int singleNum = nums.Single(x => x == 4); // 4
43. 43
Dictionaries hold {key value} pairs
.Keys holds a set of unique keys
.Values holds a collection of values
Iterating over dictionary takes the entries as
KeyValuePair<K, V>
Dictionary<K, V> vs.
SortedDictionary<K, V>
Lambda and LINQ dramatically simplifies
collection processing
Summary
45. License
This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-
NonCommercial-ShareAlike 4.0 International" license
45
46. Trainings @ Software University (SoftUni)
Software University – High-Quality Education,
Profession and Job for Software Developers
softuni.bg
Software University Foundation
http://softuni.foundation/
Software University @ Facebook
facebook.com/SoftwareUniversity
Software University Forums
forum.softuni.bg