SlideShare a Scribd company logo
Dictionaries, Lambda and LINQ
Collections and Queries
SoftUni Team
Technical Trainers
Software University
http://softuni.bg
2
 1. Associative Arrays
 Dictionary <key, value>
 2. Lambda Functions and LINQ
 Filtering, Mapping, Ordering
Table of Contents
3
Have a Question?
sli.do
#tech-softuni
Associative Arrays
Dictionary<Key, Value>
ivan
gosho
pesho
0845-346-356
2350-452-167
1255-377-131
 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
Dictionary Example – Phonebook
var phonebook = new Dictionary<string, string>();
phonebook["John Smith"] = "+1-555-8976";
phonebook["Lisa Smith"] = "+1-555-1234";
phonebook["Sam Doe"] = "+1-555-5030";
phonebook["Nakov"] = "+359-899-555-592";
phonebook["Nakov"] = "+359-2-981-9819"; // Replace
phonebook.Remove("John Smith");
foreach (var pair in phonebook)
Console.WriteLine("{0} --> {1}",
pair.Key, pair.Value);
6
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>();
 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
 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)
Traditional Dictionary: Add()
10
Dictionary<string, string>
Key Value
Hash Function
Pesho 0881-123-987
Gosho 0881-123-789
Alice 0881-123-978
Dictionary: Remove()
11
Dictionary<string, string>
Key Value
Hash Function
Pesho Pesho 0881-123-987
Gosho 0881-123-789
Alice 0881-123-978
Pesho 0881-123-987
SortedDictionary<K, V> – Example
12
SortedDictionary
<string, string>
Key Value
Alice +359-899-55-592
Comparator
Function
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
 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
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
16
SortedDictionary Example – Events
var events = new SortedDictionary<DateTime, string>();
events[new DateTime(1998, 9, 4)] = "Google's birth date";
events[new DateTime(2013, 11, 5)] = "SoftUni's birth date";
events[new DateTime(1975, 4, 4)] = "Microsoft's birth date";
events[new DateTime(2004, 2, 4)] = "Facebook's birth date";
events[new DateTime(2013, 11, 5)] = "SoftUni was founded";
foreach (var entry in events)
{
Console.WriteLine("{0:dd-MMM-yyyy}: {1}",
entry.Key, entry.Value);
}
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
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
Associative Arrays
Live Exercises in Class
Lambda Functions and LINQ
LINQ in Action: Filtering, Mapping, Ordering
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
 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
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
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
25
Converting Collections
 Using ToArray(), ToList() to convert collections:
int[] nums = Console.ReadLine()
.Split()
.Select(number => int.Parse(number))
.ToArray();
List<double> nums = Console.ReadLine()
.Split()
.Select(double.Parse)
.ToList();
26
Sorting Collections
 Using OrderBy() to sort collections:
 Using OrderByDescending() to sort collections:
List<int> nums = { 1, 5, 2, 4, 3 };
nums = nums
.OrderBy(num => num)
.ToList();
List<int> nums = { 1, 5, 2, 4, 3 };
nums = nums.OrderByDescending(num => num).ToList();
Console.WriteLine(String.Join(", ", nums));
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
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
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
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
 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
 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; }
33
Filter Collections
 Using Where(), Count():
int[] nums = { 1, 2, 3, 4, 5, 6};
nums = nums
.Where(num => num % 2 == 0)
.ToArray();
// nums = [2, 4, 6]
int[] nums = { 1, 2, 3, 4, 5, 6};
int count = nums.Count(num => num % 2 == 0);
// count = 3
34
Filtering and Sorting with Lambda Functions
int[] nums = { 11, 99, 33, 55, 77, 44, 66, 22, 88 };
nums.OrderBy(x => x).Take(3);
// 11 22 33
nums.Where(x => x < 50);
// 11 33 44 22
nums.Count(x => x % 2 == 1);
// 5
nums.Select(x => x * 2).Take(5);
// 22 198 66 110 154
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
 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
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
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
39
Other Operations over Collections
 Using Reverse()
 Using Concat():
int[] nums = { 1, 2, 3, 4, 5, 6};
nums = nums.Reverse();
// nums = 6, 5, 4, 3, 2, 1
int[] nums = { 1, 2, 3, 4, 5, 6 };
int[] otherNums = { 7, 8, 9, 0 };
nums = nums.Concat(otherNums);
// nums = 1, 2, 3, 4, 5, 6, 7, 8, 9, 0
40
 Read an array of 4*k integers, fold it like shown below, and print
the sum of the upper and lower rows (2*k integers):
Problem: Fold and Sum
1 2 3 4 5 6 7 8
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/174#5
2 1 8 7
3 4 5 6
5 5 13 13
4 3 -1 2 5 0 1 9 8 6 7 -2
-1 3 4 -2 7 6
2 5 0 1 9 8
1 8 4 -1 16 14
5 2 3 6
5 6
2 3
7 9
3 4 5 6
3 4 5 6
41
Solution: Fold and Sum
int[] arr = Console.ReadLine()
.Split(' ').Select(int.Parse).ToArray();
int k = arr.Length / 4;
int[] row1left = arr.Take(k).Reverse().ToArray();
int[] row1right = arr.Reverse().Take(k).ToArray();
int[] row1 = row1left.Concat(row1right).ToArray();
int[] row2 = arr.Skip(k).Take(2 * k).ToArray();
var sumArr =
row1.Select((x, index) => x + row2[index]);
Console.WriteLine(string.Join(" ", sumArr));
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/174#5
Lambda Expressions and LINQ
Live Exercises in Class (Lab)
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
?
Programming Fundamentals – Dictionaries
https://softuni.bg/courses/programming-fundamentals
License
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-
NonCommercial-ShareAlike 4.0 International" license
45
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

More Related Content

PPTX
clean code book summary - uncle bob - English version
PPT
Sql injection
PPTX
Java script
PPTX
SQL Injection
PPTX
PPTX
Clean Code Principles
PDF
Java 8 Lambda Expressions
PPTX
Arrays in Java
clean code book summary - uncle bob - English version
Sql injection
Java script
SQL Injection
Clean Code Principles
Java 8 Lambda Expressions
Arrays in Java

What's hot (20)

PPTX
Super keyword in java
PDF
CNIT 129S: 9: Attacking Data Stores (Part 2 of 2)
PPT
Sql injection
PPT
Javascript arrays
PPTX
Hash table in java
PDF
Java conditional statements
PDF
Penetration testing web application web application (in) security
PPT
PHP - Introduction to PHP Forms
PPTX
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
PDF
PHP Loops and PHP Forms
PPTX
Bsc cs ii dfs u-1 introduction to data structure
PPTX
Sql injection
PPT
SQL subquery
PPTX
String, string builder, string buffer
PPT
plsql.ppt
PPTX
SQL injection
PDF
JUnit & Mockito, first steps
PPTX
MULTI THREADING IN JAVA
PDF
JavaScript - Chapter 12 - Document Object Model
Super keyword in java
CNIT 129S: 9: Attacking Data Stores (Part 2 of 2)
Sql injection
Javascript arrays
Hash table in java
Java conditional statements
Penetration testing web application web application (in) security
PHP - Introduction to PHP Forms
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
PHP Loops and PHP Forms
Bsc cs ii dfs u-1 introduction to data structure
Sql injection
SQL subquery
String, string builder, string buffer
plsql.ppt
SQL injection
JUnit & Mockito, first steps
MULTI THREADING IN JAVA
JavaScript - Chapter 12 - Document Object Model
Ad

Similar to Chapter 22. Lambda Expressions and LINQ (20)

PPT
Generics collections
DOCX
First approach in linq
PPTX
Functional programming (Let's fall back in love with Programming)
PPTX
16. Arrays Lists Stacks Queues
PPT
Generics Collections
PPTX
FP Day 2011 - Turning to the Functional Side (using C# & F#)
PPTX
07. Arrays
PPTX
18. Dictionaries, Hash-Tables and Set
PDF
Dictionary and sets-converted
PDF
LectureNotes-03-DSA
PPTX
LINQ.pptx
PPTX
.Net Collection Classes Deep Dive - Rocksolid Tour 2013
PPTX
COLLECTIONS.pptx
PPTX
Collection
PDF
Amusing C#
PPTX
18. Java associative arrays
KEY
関数潮流(Function Tendency)
PDF
Coding with LINQ, Patterns & Practices
PPT
Data Structure In C#
PDF
FSharp Talk
Generics collections
First approach in linq
Functional programming (Let's fall back in love with Programming)
16. Arrays Lists Stacks Queues
Generics Collections
FP Day 2011 - Turning to the Functional Side (using C# & F#)
07. Arrays
18. Dictionaries, Hash-Tables and Set
Dictionary and sets-converted
LectureNotes-03-DSA
LINQ.pptx
.Net Collection Classes Deep Dive - Rocksolid Tour 2013
COLLECTIONS.pptx
Collection
Amusing C#
18. Java associative arrays
関数潮流(Function Tendency)
Coding with LINQ, Patterns & Practices
Data Structure In C#
FSharp Talk
Ad

More from Intro C# Book (20)

PPTX
17. Java data structures trees representation and traversal
PPTX
Java Problem solving
PPTX
21. Java High Quality Programming Code
PPTX
20.5 Java polymorphism
PPTX
20.4 Java interfaces and abstraction
PPTX
20.3 Java encapsulation
PPTX
20.2 Java inheritance
PPTX
20.1 Java working with abstraction
PPTX
19. Java data structures algorithms and complexity
PPTX
16. Java stacks and queues
PPTX
14. Java defining classes
PPTX
13. Java text processing
PPTX
12. Java Exceptions and error handling
PPTX
11. Java Objects and classes
PPTX
09. Java Methods
PPTX
05. Java Loops Methods and Classes
PPTX
07. Java Array, Set and Maps
PPTX
03 and 04 .Operators, Expressions, working with the console and conditional s...
PPTX
02. Data Types and variables
PPTX
01. Introduction to programming with java
17. Java data structures trees representation and traversal
Java Problem solving
21. Java High Quality Programming Code
20.5 Java polymorphism
20.4 Java interfaces and abstraction
20.3 Java encapsulation
20.2 Java inheritance
20.1 Java working with abstraction
19. Java data structures algorithms and complexity
16. Java stacks and queues
14. Java defining classes
13. Java text processing
12. Java Exceptions and error handling
11. Java Objects and classes
09. Java Methods
05. Java Loops Methods and Classes
07. Java Array, Set and Maps
03 and 04 .Operators, Expressions, working with the console and conditional s...
02. Data Types and variables
01. Introduction to programming with java

Recently uploaded (20)

PPTX
Introduction about ICD -10 and ICD11 on 5.8.25.pptx
PDF
Introduction to the IoT system, how the IoT system works
PDF
FINAL CALL-6th International Conference on Networks & IOT (NeTIOT 2025)
PPT
Design_with_Watersergyerge45hrbgre4top (1).ppt
PDF
💰 𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓 💰
PPTX
Introuction about ICD -10 and ICD-11 PPT.pptx
PDF
Testing WebRTC applications at scale.pdf
PDF
WebRTC in SignalWire - troubleshooting media negotiation
PPT
isotopes_sddsadsaadasdasdasdasdsa1213.ppt
PDF
Decoding a Decade: 10 Years of Applied CTI Discipline
PDF
An introduction to the IFRS (ISSB) Stndards.pdf
PPTX
introduction about ICD -10 & ICD-11 ppt.pptx
PDF
Cloud-Scale Log Monitoring _ Datadog.pdf
PPTX
Funds Management Learning Material for Beg
PDF
Sims 4 Historia para lo sims 4 para jugar
PPTX
PptxGenJS_Demo_Chart_20250317130215833.pptx
PDF
Slides PDF The World Game (s) Eco Economic Epochs.pdf
PDF
Automated vs Manual WooCommerce to Shopify Migration_ Pros & Cons.pdf
PPTX
Module 1 - Cyber Law and Ethics 101.pptx
PPTX
Introduction to Information and Communication Technology
Introduction about ICD -10 and ICD11 on 5.8.25.pptx
Introduction to the IoT system, how the IoT system works
FINAL CALL-6th International Conference on Networks & IOT (NeTIOT 2025)
Design_with_Watersergyerge45hrbgre4top (1).ppt
💰 𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓 💰
Introuction about ICD -10 and ICD-11 PPT.pptx
Testing WebRTC applications at scale.pdf
WebRTC in SignalWire - troubleshooting media negotiation
isotopes_sddsadsaadasdasdasdasdsa1213.ppt
Decoding a Decade: 10 Years of Applied CTI Discipline
An introduction to the IFRS (ISSB) Stndards.pdf
introduction about ICD -10 & ICD-11 ppt.pptx
Cloud-Scale Log Monitoring _ Datadog.pdf
Funds Management Learning Material for Beg
Sims 4 Historia para lo sims 4 para jugar
PptxGenJS_Demo_Chart_20250317130215833.pptx
Slides PDF The World Game (s) Eco Economic Epochs.pdf
Automated vs Manual WooCommerce to Shopify Migration_ Pros & Cons.pdf
Module 1 - Cyber Law and Ethics 101.pptx
Introduction to Information and Communication Technology

Chapter 22. Lambda Expressions and LINQ

  • 1. Dictionaries, Lambda and LINQ Collections and Queries SoftUni Team Technical Trainers Software University http://softuni.bg
  • 2. 2  1. Associative Arrays  Dictionary <key, value>  2. Lambda Functions and LINQ  Filtering, Mapping, Ordering Table of Contents
  • 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
  • 6. Dictionary Example – Phonebook var phonebook = new Dictionary<string, string>(); phonebook["John Smith"] = "+1-555-8976"; phonebook["Lisa Smith"] = "+1-555-1234"; phonebook["Sam Doe"] = "+1-555-5030"; phonebook["Nakov"] = "+359-899-555-592"; phonebook["Nakov"] = "+359-2-981-9819"; // Replace phonebook.Remove("John Smith"); foreach (var pair in phonebook) Console.WriteLine("{0} --> {1}", pair.Key, pair.Value); 6
  • 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)
  • 10. Traditional Dictionary: Add() 10 Dictionary<string, string> Key Value Hash Function Pesho 0881-123-987 Gosho 0881-123-789 Alice 0881-123-978
  • 11. Dictionary: Remove() 11 Dictionary<string, string> Key Value Hash Function Pesho Pesho 0881-123-987 Gosho 0881-123-789 Alice 0881-123-978
  • 12. Pesho 0881-123-987 SortedDictionary<K, V> – Example 12 SortedDictionary <string, string> Key Value Alice +359-899-55-592 Comparator Function
  • 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
  • 16. 16 SortedDictionary Example – Events var events = new SortedDictionary<DateTime, string>(); events[new DateTime(1998, 9, 4)] = "Google's birth date"; events[new DateTime(2013, 11, 5)] = "SoftUni's birth date"; events[new DateTime(1975, 4, 4)] = "Microsoft's birth date"; events[new DateTime(2004, 2, 4)] = "Facebook's birth date"; events[new DateTime(2013, 11, 5)] = "SoftUni was founded"; foreach (var entry in events) { Console.WriteLine("{0:dd-MMM-yyyy}: {1}", entry.Key, entry.Value); }
  • 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
  • 20. Lambda Functions and LINQ LINQ in Action: Filtering, Mapping, Ordering
  • 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
  • 25. 25 Converting Collections  Using ToArray(), ToList() to convert collections: int[] nums = Console.ReadLine() .Split() .Select(number => int.Parse(number)) .ToArray(); List<double> nums = Console.ReadLine() .Split() .Select(double.Parse) .ToList();
  • 26. 26 Sorting Collections  Using OrderBy() to sort collections:  Using OrderByDescending() to sort collections: List<int> nums = { 1, 5, 2, 4, 3 }; nums = nums .OrderBy(num => num) .ToList(); List<int> nums = { 1, 5, 2, 4, 3 }; nums = nums.OrderByDescending(num => num).ToList(); Console.WriteLine(String.Join(", ", nums));
  • 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; }
  • 33. 33 Filter Collections  Using Where(), Count(): int[] nums = { 1, 2, 3, 4, 5, 6}; nums = nums .Where(num => num % 2 == 0) .ToArray(); // nums = [2, 4, 6] int[] nums = { 1, 2, 3, 4, 5, 6}; int count = nums.Count(num => num % 2 == 0); // count = 3
  • 34. 34 Filtering and Sorting with Lambda Functions int[] nums = { 11, 99, 33, 55, 77, 44, 66, 22, 88 }; nums.OrderBy(x => x).Take(3); // 11 22 33 nums.Where(x => x < 50); // 11 33 44 22 nums.Count(x => x % 2 == 1); // 5 nums.Select(x => x * 2).Take(5); // 22 198 66 110 154
  • 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
  • 39. 39 Other Operations over Collections  Using Reverse()  Using Concat(): int[] nums = { 1, 2, 3, 4, 5, 6}; nums = nums.Reverse(); // nums = 6, 5, 4, 3, 2, 1 int[] nums = { 1, 2, 3, 4, 5, 6 }; int[] otherNums = { 7, 8, 9, 0 }; nums = nums.Concat(otherNums); // nums = 1, 2, 3, 4, 5, 6, 7, 8, 9, 0
  • 40. 40  Read an array of 4*k integers, fold it like shown below, and print the sum of the upper and lower rows (2*k integers): Problem: Fold and Sum 1 2 3 4 5 6 7 8 Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/174#5 2 1 8 7 3 4 5 6 5 5 13 13 4 3 -1 2 5 0 1 9 8 6 7 -2 -1 3 4 -2 7 6 2 5 0 1 9 8 1 8 4 -1 16 14 5 2 3 6 5 6 2 3 7 9 3 4 5 6 3 4 5 6
  • 41. 41 Solution: Fold and Sum int[] arr = Console.ReadLine() .Split(' ').Select(int.Parse).ToArray(); int k = arr.Length / 4; int[] row1left = arr.Take(k).Reverse().ToArray(); int[] row1right = arr.Reverse().Take(k).ToArray(); int[] row1 = row1left.Concat(row1right).ToArray(); int[] row2 = arr.Skip(k).Take(2 * k).ToArray(); var sumArr = row1.Select((x, index) => x + row2[index]); Console.WriteLine(string.Join(" ", sumArr)); Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/174#5
  • 42. Lambda Expressions and LINQ Live Exercises in Class (Lab)
  • 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
  • 44. ? Programming Fundamentals – Dictionaries https://softuni.bg/courses/programming-fundamentals
  • 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

Editor's Notes

  • #11: © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
  • #12: © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
  • #13: © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
  • #14: © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.