SlideShare a Scribd company logo
1 of 46
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

What's hot (20)

Complexity analysis in Algorithms
Complexity analysis in AlgorithmsComplexity analysis in Algorithms
Complexity analysis in Algorithms
 
Waf bypassing Techniques
Waf bypassing TechniquesWaf bypassing Techniques
Waf bypassing Techniques
 
Subdomain Takeover
Subdomain TakeoverSubdomain Takeover
Subdomain Takeover
 
Hash table in data structure and algorithm
Hash table in data structure and algorithmHash table in data structure and algorithm
Hash table in data structure and algorithm
 
Jdbc Ppt
Jdbc PptJdbc Ppt
Jdbc Ppt
 
2D Array
2D Array 2D Array
2D Array
 
I'm in ur browser, pwning your stuff - Attacking (with) Google Chrome Extensions
I'm in ur browser, pwning your stuff - Attacking (with) Google Chrome ExtensionsI'm in ur browser, pwning your stuff - Attacking (with) Google Chrome Extensions
I'm in ur browser, pwning your stuff - Attacking (with) Google Chrome Extensions
 
String Matching Finite Automata & KMP Algorithm.
String Matching Finite Automata & KMP Algorithm.String Matching Finite Automata & KMP Algorithm.
String Matching Finite Automata & KMP Algorithm.
 
Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In Java
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
 
Ch03-Software Engineering Model
Ch03-Software Engineering ModelCh03-Software Engineering Model
Ch03-Software Engineering Model
 
Hashing
HashingHashing
Hashing
 
Heap sort
Heap sortHeap sort
Heap sort
 
Java GC
Java GCJava GC
Java GC
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraLambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
 
String matching algorithms
String matching algorithmsString matching algorithms
String matching algorithms
 
Branch and bound
Branch and boundBranch and bound
Branch and bound
 
Address calculation-sort
Address calculation-sortAddress calculation-sort
Address calculation-sort
 
Daa notes 3
Daa notes 3Daa notes 3
Daa notes 3
 

Similar to Chapter 22. Lambda Expressions and LINQ

18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arraysIntro C# Book
 
Legacy lambda code
Legacy lambda codeLegacy lambda code
Legacy lambda codePeter Lawrey
 
Programming python quick intro for schools
Programming python quick intro for schoolsProgramming python quick intro for schools
Programming python quick intro for schoolsDan Bowen
 
Introduction to python programming 1
Introduction to python programming   1Introduction to python programming   1
Introduction to python programming 1Giovanni Della Lunga
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnArnaud Joly
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoThe Software House
 
iRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat SheetiRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat SheetSamuel Lampa
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a ElixirSvet Ivantchev
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++Neeru Mittal
 
Python lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionPython lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionARVIND PANDE
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala Knoldus Inc.
 
Elixir in a nutshell - Fundamental Concepts
Elixir in a nutshell - Fundamental ConceptsElixir in a nutshell - Fundamental Concepts
Elixir in a nutshell - Fundamental ConceptsHéla Ben Khalfallah
 
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programmingVisnuDharsini
 
Chapter 2&3 (java fundamentals and Control Structures).ppt
Chapter 2&3 (java fundamentals and Control Structures).pptChapter 2&3 (java fundamentals and Control Structures).ppt
Chapter 2&3 (java fundamentals and Control Structures).ppthenokmetaferia1
 

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

07. Arrays
07. Arrays07. Arrays
07. Arrays
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
 
Legacy lambda code
Legacy lambda codeLegacy lambda code
Legacy lambda code
 
Programming python quick intro for schools
Programming python quick intro for schoolsProgramming python quick intro for schools
Programming python quick intro for schools
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
Introduction to python programming 1
Introduction to python programming   1Introduction to python programming   1
Introduction to python programming 1
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
 
Learn Matlab
Learn MatlabLearn Matlab
Learn Matlab
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
 
iRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat SheetiRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat Sheet
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a Elixir
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
 
Python lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionPython lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce function
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
 
bobok
bobokbobok
bobok
 
Elixir in a nutshell - Fundamental Concepts
Elixir in a nutshell - Fundamental ConceptsElixir in a nutshell - Fundamental Concepts
Elixir in a nutshell - Fundamental Concepts
 
Programming in R
Programming in RProgramming in R
Programming in R
 
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programming
 
Chapter 2&3 (java fundamentals and Control Structures).ppt
Chapter 2&3 (java fundamentals and Control Structures).pptChapter 2&3 (java fundamentals and Control Structures).ppt
Chapter 2&3 (java fundamentals and Control Structures).ppt
 

More from Intro C# Book

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversalIntro C# Book
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving Intro C# Book
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming CodeIntro C# Book
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism Intro C# Book
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstractionIntro C# Book
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulationIntro C# Book
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritanceIntro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexityIntro C# Book
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queuesIntro C# Book
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classesIntro C# Book
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processingIntro C# Book
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handlingIntro C# Book
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classesIntro C# Book
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and ClassesIntro C# Book
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and MapsIntro C# Book
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variablesIntro C# Book
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with javaIntro C# Book
 

More from Intro C# Book (20)

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
 

Recently uploaded

Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts servicesonalikaur4
 
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...aditipandeya
 
VIP Kolkata Call Girl Alambazar 👉 8250192130 Available With Room
VIP Kolkata Call Girl Alambazar 👉 8250192130  Available With RoomVIP Kolkata Call Girl Alambazar 👉 8250192130  Available With Room
VIP Kolkata Call Girl Alambazar 👉 8250192130 Available With Roomdivyansh0kumar0
 
Gram Darshan PPT cyber rural in villages of india
Gram Darshan PPT cyber rural  in villages of indiaGram Darshan PPT cyber rural  in villages of india
Gram Darshan PPT cyber rural in villages of indiaimessage0108
 
AlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsAlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsThierry TROUIN ☁
 
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine ServiceHot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Servicesexy call girls service in goa
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012rehmti665
 
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...Diya Sharma
 
How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)Damian Radcliffe
 
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...APNIC
 
Russian Call Girls in Kolkata Samaira 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Samaira 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Samaira 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Samaira 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girlsstephieert
 
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on DeliveryCall Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Deliverybabeytanya
 
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Russian Call girls in Dubai +971563133746 Dubai Call girls
Russian  Call girls in Dubai +971563133746 Dubai  Call girlsRussian  Call girls in Dubai +971563133746 Dubai  Call girls
Russian Call girls in Dubai +971563133746 Dubai Call girlsstephieert
 
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With RoomVIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Roomishabajaj13
 
Chennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts servicevipmodelshub1
 

Recently uploaded (20)

Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
 
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
 
VIP Kolkata Call Girl Alambazar 👉 8250192130 Available With Room
VIP Kolkata Call Girl Alambazar 👉 8250192130  Available With RoomVIP Kolkata Call Girl Alambazar 👉 8250192130  Available With Room
VIP Kolkata Call Girl Alambazar 👉 8250192130 Available With Room
 
Gram Darshan PPT cyber rural in villages of india
Gram Darshan PPT cyber rural  in villages of indiaGram Darshan PPT cyber rural  in villages of india
Gram Darshan PPT cyber rural in villages of india
 
AlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsAlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with Flows
 
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine ServiceHot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
 
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
 
How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)
 
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
 
Russian Call Girls in Kolkata Samaira 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Samaira 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Samaira 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Samaira 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
 
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
Call Girls In South Ex 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In South Ex 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICECall Girls In South Ex 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In South Ex 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
 
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on DeliveryCall Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
 
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
 
Russian Call girls in Dubai +971563133746 Dubai Call girls
Russian  Call girls in Dubai +971563133746 Dubai  Call girlsRussian  Call girls in Dubai +971563133746 Dubai  Call girls
Russian Call girls in Dubai +971563133746 Dubai Call girls
 
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
 
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With RoomVIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
 
Chennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts service
 

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

  1. © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
  2. © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
  3. © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
  4. © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.