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

What's hot (20)

PPT
Restricting and Sorting Data - Oracle Data Base
Salman Memon
 
PDF
Working with JSON Data in PostgreSQL vs. MongoDB
ScaleGrid.io
 
PDF
[APJ] Common Table Expressions (CTEs) in SQL
EDB
 
PPTX
Elastic Stack Introduction
Vikram Shinde
 
PDF
MongoDB World 2019: The Sights (and Smells) of a Bad Query
MongoDB
 
PDF
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
PPT
skip list
iammutex
 
PPTX
elasticsearch_적용 및 활용_정리
Junyi Song
 
PDF
MongoDB World 2019: Tips and Tricks++ for Querying and Indexing MongoDB
MongoDB
 
PDF
SQL Functions and Operators
Mohan Kumar.R
 
PPTX
Dictionaries and Sets
Munazza-Mah-Jabeen
 
PDF
MySQL 8.0 Optimizer Guide
Morgan Tocker
 
PPTX
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
PDF
MySQL Performance Schema in Action
Sveta Smirnova
 
PPT
Functions in C++
Sachin Sharma
 
PPTX
SQL Functions
ammarbrohi
 
PDF
Operating system lab task
hammad1515
 
PPTX
SQL
Vineeta Garg
 
PDF
MongoDB .local Toronto 2019: Tips and Tricks for Effective Indexing
MongoDB
 
Restricting and Sorting Data - Oracle Data Base
Salman Memon
 
Working with JSON Data in PostgreSQL vs. MongoDB
ScaleGrid.io
 
[APJ] Common Table Expressions (CTEs) in SQL
EDB
 
Elastic Stack Introduction
Vikram Shinde
 
MongoDB World 2019: The Sights (and Smells) of a Bad Query
MongoDB
 
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
skip list
iammutex
 
elasticsearch_적용 및 활용_정리
Junyi Song
 
MongoDB World 2019: Tips and Tricks++ for Querying and Indexing MongoDB
MongoDB
 
SQL Functions and Operators
Mohan Kumar.R
 
Dictionaries and Sets
Munazza-Mah-Jabeen
 
MySQL 8.0 Optimizer Guide
Morgan Tocker
 
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
MySQL Performance Schema in Action
Sveta Smirnova
 
Functions in C++
Sachin Sharma
 
SQL Functions
ammarbrohi
 
Operating system lab task
hammad1515
 
MongoDB .local Toronto 2019: Tips and Tricks for Effective Indexing
MongoDB
 

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

PPTX
07. Arrays
Intro C# Book
 
PPTX
18. Java associative arrays
Intro C# Book
 
PPTX
PPT_1_9102501a-a7a1-493e-818f-cf699918bbf6.pptx
myatminsoe180
 
PPTX
Legacy lambda code
Peter Lawrey
 
PPTX
Programming python quick intro for schools
Dan Bowen
 
PPT
ComandosDePython_ComponentesBasicosImpl.ppt
oscarJulianPerdomoCh1
 
PDF
Spark workshop
Wojciech Pituła
 
PPTX
Introduction to python programming 1
Giovanni Della Lunga
 
PPTX
Java Foundations: Maps, Lambda and Stream API
Svetlin Nakov
 
PDF
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Arnaud Joly
 
PPTX
matlab presentation fro engninering students
SyedSadiq73
 
PPT
Learn Matlab
Abd El Kareem Ahmed
 
PDF
Refactoring to Macros with Clojure
Dmitry Buzdin
 
PDF
Developer Experience i TypeScript. Najbardziej ikoniczne duo
The Software House
 
PDF
iRODS Rule Language Cheat Sheet
Samuel Lampa
 
PDF
Introducción a Elixir
Svet Ivantchev
 
PPTX
Library functions in c++
Neeru Mittal
 
PPTX
Chp7_C++_Functions_Part1_Built-in functions.pptx
ssuser10ed71
 
PDF
Python lambda functions with filter, map & reduce function
ARVIND PANDE
 
PPTX
Python-Dictionaries.pptx easy way to learn dictionaries
panchalneha692
 
07. Arrays
Intro C# Book
 
18. Java associative arrays
Intro C# Book
 
PPT_1_9102501a-a7a1-493e-818f-cf699918bbf6.pptx
myatminsoe180
 
Legacy lambda code
Peter Lawrey
 
Programming python quick intro for schools
Dan Bowen
 
ComandosDePython_ComponentesBasicosImpl.ppt
oscarJulianPerdomoCh1
 
Spark workshop
Wojciech Pituła
 
Introduction to python programming 1
Giovanni Della Lunga
 
Java Foundations: Maps, Lambda and Stream API
Svetlin Nakov
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Arnaud Joly
 
matlab presentation fro engninering students
SyedSadiq73
 
Learn Matlab
Abd El Kareem Ahmed
 
Refactoring to Macros with Clojure
Dmitry Buzdin
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
The Software House
 
iRODS Rule Language Cheat Sheet
Samuel Lampa
 
Introducción a Elixir
Svet Ivantchev
 
Library functions in c++
Neeru Mittal
 
Chp7_C++_Functions_Part1_Built-in functions.pptx
ssuser10ed71
 
Python lambda functions with filter, map & reduce function
ARVIND PANDE
 
Python-Dictionaries.pptx easy way to learn dictionaries
panchalneha692
 
Ad

More from Intro C# Book (20)

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

Recently uploaded (20)

PDF
B M Mostofa Kamal Al-Azad [Document & Localization Expert]
Mostofa Kamal Al-Azad
 
PDF
Clive Dickens RedTech Public Copy - Collaborate or Die
Clive Dickens
 
PDF
web application development company in bangalore.pdf
https://dkpractice.co.in/seo.html tech
 
PDF
Google Chrome vs Other Browsers: Why Users Still Prefer It.pdf
hgfdsqetuiplmnvcz43
 
PPTX
The ARUBA Kind of new Proposal Umum .pptx
andiwarneri
 
PDF
Download Google Chrome for Fast and Secure Web Browsing Experience
hgfdsqetuiplmnvcz43
 
PDF
Materi tentang From Digital Economy to Fintech.pdf
Abdul Hakim
 
PDF
The Convergence of Threat Behaviors Across Intrusions
Joe Slowik
 
PPTX
BitRecover OST to PST Converter Software
antoniogosling01
 
PPTX
Q1 English3 Week5 [email protected]
JenniferCawaling1
 
PDF
03 Internal Analysis Strategik Manajemen.pdf
AhmadRifaldhi
 
PDF
BroadLink Cloud Service introduction.pdf
DevendraDwivdi1
 
PPTX
原版一样(ANU毕业证书)澳洲澳大利亚国立大学毕业证在线购买
Taqyea
 
PDF
What Is Google Chrome? Fast & Secure Web Browser Guide
hgfdsqetuiplmnvcz43
 
PDF
ContextForge MCP Gateway - the missing proxy for AI Agents and Tools
Mihai Criveti
 
PDF
Beginning-Laravel-Build-Websites-with-Laravel-5.8-by-Sanjib-Sinha-z-lib.org.pdf
TagumLibuganonRiverB
 
PDF
I Want to join occult brotherhood for money ritual#((+2347089754903))
haragonoccult
 
PPTX
My Mother At 66! (2).pptx00000000000000000000000000000
vedapattisiddharth
 
PDF
Slides: Eco Economic Epochs for The World Game (s) pdf
Steven McGee
 
PPT
Almos Entirely Correct Mixing with Apps to Voting
gapati2964
 
B M Mostofa Kamal Al-Azad [Document & Localization Expert]
Mostofa Kamal Al-Azad
 
Clive Dickens RedTech Public Copy - Collaborate or Die
Clive Dickens
 
web application development company in bangalore.pdf
https://dkpractice.co.in/seo.html tech
 
Google Chrome vs Other Browsers: Why Users Still Prefer It.pdf
hgfdsqetuiplmnvcz43
 
The ARUBA Kind of new Proposal Umum .pptx
andiwarneri
 
Download Google Chrome for Fast and Secure Web Browsing Experience
hgfdsqetuiplmnvcz43
 
Materi tentang From Digital Economy to Fintech.pdf
Abdul Hakim
 
The Convergence of Threat Behaviors Across Intrusions
Joe Slowik
 
BitRecover OST to PST Converter Software
antoniogosling01
 
03 Internal Analysis Strategik Manajemen.pdf
AhmadRifaldhi
 
BroadLink Cloud Service introduction.pdf
DevendraDwivdi1
 
原版一样(ANU毕业证书)澳洲澳大利亚国立大学毕业证在线购买
Taqyea
 
What Is Google Chrome? Fast & Secure Web Browser Guide
hgfdsqetuiplmnvcz43
 
ContextForge MCP Gateway - the missing proxy for AI Agents and Tools
Mihai Criveti
 
Beginning-Laravel-Build-Websites-with-Laravel-5.8-by-Sanjib-Sinha-z-lib.org.pdf
TagumLibuganonRiverB
 
I Want to join occult brotherhood for money ritual#((+2347089754903))
haragonoccult
 
My Mother At 66! (2).pptx00000000000000000000000000000
vedapattisiddharth
 
Slides: Eco Economic Epochs for The World Game (s) pdf
Steven McGee
 
Almos Entirely Correct Mixing with Apps to Voting
gapati2964
 

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.