LINQ and Lambda Expressions Telerik Software Academy LINQ Overview.

Slides:



Advertisements
Similar presentations
Lambda Expressions Matt Van Horn Software Engineer Iverson Gaming Systems, Inc.
Advertisements

The Microsoft Technical Roadshow 2007 Language Enhancements and LINQ Daniel Moth Developer & Platform Group Microsoft Ltd
LINQ and Collections An introduction to LINQ and Collections.
Extension Methods, Anonymous Types LINQ Query Keywords, Lambda Expressions Svetlin Nakov Telerik Corporation
.NET 3.5 – Mysteries. NetFx Evolution NetFx 1.0 C# 1.0, VB 7.0, VS.NET NetFx 1.1 C# 1.1, VB 7.1, VS 2003 NetFx 2.0 C# 2.0, VB 8.0, VS 2005 NetFx 3.0 C#
C# and LINQ Yuan Yu Microsoft Research Silicon Valley.
RPN and Shunting-yard algorithm Ivaylo Kenov Telerik Software Academy academy.telerik.com Technical Assistant
C# 3.0 Tom Roeder CS fa. Version 3 From PDC 2005 preview compiler available LINQ: language-integrated query High level points: adds native query.
2.3 Cool features in C# academy.zariba.com 1. Lecture Content 1.Extension Methods 2.Anonymous Types 3.Delegates 4.Action and Func 5.Events 6.Lambda Expressions.
A tour of new features introducing LINQ. Agenda of LINQ Presentation We have features for every step of the way LINQ Fundamentals Anonymous Functions/Lambda.
Trees, Tre-Like Structures, Binary Search Trees, Balanced Trees, Tree Traversals, DFS and BFS Svetlin Nakov Telerik Software Academy academy.telerik.com.
Data-tier Application, Import, Refactoring, Publish, Schema Comparison, Database Unit Testing Borislav Statev Telerik Software Academy academy.telerik.com.
XML files (with LINQ). Introduction to LINQ ( Language Integrated Query ) C#’s new LINQ capabilities allow you to write query expressions that retrieve.
LINQ Programming in C# LINQ CSE Prof. Roger Crawfis.
 Introduction  What is LINQ  Syntax  How to Query  Example Program.
LINQ, An IntroLINQ, An Intro Florin−Tudor Cristea, Microsoft Student Partner.
Eric Vogel Software Developer A.J. Boggs & Company.
Operators, Expressions, Projections, Aggregations Svetlin Nakov Telerik Corporation
Arrays, Lists, Stacks, Queues Static and Dynamic Implementation Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer
Lambdas and Streams. Functional interfaces Functional interfaces are also known as single abstract method (SAM) interfaces. Package java.util.function.
Extension Methods, Lambda Expressions, LINQ Operators, Expressions, Projections, Aggregations Extension Methods, Lambda Expressions, LINQ Operators, Expressions,
Dictionaries, Hash Tables, Hashing, Collisions, Sets Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Putting it all together: LINQ as an Example. The Problem: SQL in Code Programs often connect to database servers. Database servers only “speak” SQL. Programs.
Advanced C#, part IV Niels Hallenberg IT University of Copenhagen (With thanks to Peter Sestoft and Kasper Østerbye) BAAAP – Spring 2009.
Functional Programming Extension Methods, Lambda Expressions, LINQ Svetlin Nakov Technical Trainer Software University
Extension Methods, Anonymous Types LINQ Query Keywords, Lambda Expressions Based on material from Telerik Corporation.
Introduction to C# C# is - elegant, type-safe, object oriented language enabling to build applications that run on the.NET framework - types of applications.
Introduction to LINQ Lecture # 19 August Introduction How do you interrogate/manipulate data? What if you could do the work in a type-safe," string-free.
Generics Collections. Why do we need Generics? Another method of software re-use. When we implement an algorithm, we want to re-use it for different types.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
 Language Integrated Query  Make query a part of the language  Component of.NET Framework 3.5  Shipped with Visual Studio 2008.
How to be a C# ninja in 10 easy steps Benjamin Day.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Hoang Anh Viet Hà Nội University of Technology Chapter 1. Introduction to C# Programming.
Delegates and Events Callback Functionality and Event-Driven Programming Svetlin Nakov Technical Trainer Software University
 Although VERY commonly used, arrays have limited capabilities  A List is similar to an array but provides additional functionality, such as dynamic.
Introduction to LINQ Chapter 11. Introduction Large amounts of data are often stored in a database—an organized collection of data. A database management.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
Arrays, Lists, Stacks, Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Callback Functionality and Event-Driven Programming
Computational Complexity of Fundamental Data Structures, Choosing a Data Structure.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 10 th Lecture Pavel Ježek
CSCI 3327 Visual Basic Chapter 8: Introduction to LINQ and Collections UTPA – Fall 2011.
Inside LINQ to Objects How LINQ to Objects work Inside LINQ1.
Satisfy Your Technical Curiosity C# 3.0 Raj Pai Group Program Manager Microsoft Corporation
Dictionaries, Hash Tables, Collisions Resolution, Sets Svetlin Nakov Telerik Corporation
Lecture 5 functions 1 © by Pearson Education, Inc. All Rights Reserved.
IAP C# 2011 Lecture 2: Delegates, Lambdas, LINQ Geza Kovacs.
Processing Matrices and Multidimensional Tables Telerik Software Academy C# Fundamentals – Part 2.
Language Integrated Query Mike Taulty Developer & Platform Group Microsoft Ltd
Functional Programming Extension Methods, Lambda Expressions, LINQ SoftUni Team Technical Trainers Software University
Chapter 11.  Large amounts of data are often stored in a database—an organized collection of data.  A database management system (DBMS) provides mechanisms.
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Introduction to.NET Florin Olariu “Alexandru Ioan Cuza”, University of Iai Department of Computer Science.
Functional Programming
Part 1: Overview of LINQ Intro to LINQ Presenter: PhuongNQK.
Introduction to Entity Framework
Mocking Tool for easier unit testing
Arrays, Lists, Stacks, Queues
Introduction to LINQ and Generic Collections
Entity Framework Performance
Multidimensional Arrays
Lambda Expressions By Val Feldsher.
Language Integrated Query: (LINQ) An introduction
.NET and .NET Core 9. Towards Higher Order Pan Wuming 2017.
Introduction to LINQ Chapter 11 10/28/2015 Lect 4 CT1411.
Introduction to LINQ Chapter 11.
LINQ & ADO.NET Entity Framework
CS4540 Special Topics in Web Development LINQ to Objects
Presentation transcript:

LINQ and Lambda Expressions Telerik Software Academy LINQ Overview

1. Lambda Expressions 1.Anonymous functions 2.Creating Lambda expressions 3.Action and Func 2. LINQ Queries 1.Extension methods 2.Operations with collections 2

 A lambda expression is an anonymous function containing expressions and statements  Used to create delegates or expression tree types  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 4

 Usually used with collection extension methods like FindAll() and RemoveAll() 5 List list = new List () { 1, 2, 3, 4 }; List evenNumbers = list.FindAll(x => (x % 2) == 0); list.FindAll(x => (x % 2) == 0); foreach (var num in evenNumbers) { Console.Write("{0} ", num); Console.Write("{0} ", num);}Console.WriteLine(); // 2 4 list.RemoveAll(x => x > 3); // 1 2 3

6 var pets = new { "Sharo", "Rex", "Strela", "Bora" "Sharo", "Rex", "Strela", "Bora"}; var sortedPets = pets.OrderBy(pet => pet); foreach (Pet pet in sortedPets) { Console.WriteLine("{0}", pet); Console.WriteLine("{0}", pet);}

 Lambda code expressions: 7 List list = new List () { 20, 1, 4, 8, 9, 44 }; { 20, 1, 4, 8, 9, 44 }; // Process each argument with code statements List evenNumbers = list.FindAll((i) => { Console.WriteLine("value of i is: {0}", i); Console.WriteLine("value of i is: {0}", i); return (i % 2) == 0; return (i % 2) == 0; }); }); Console.WriteLine("Here are your even numbers:"); foreach (int even in evenNumbers) Console.Write("{0}\t", even); Console.Write("{0}\t", even);

 Lambda functions can be stored in variables of type delegate  Delegates are typed references to functions  Standard function delegates in.NET:  Func, Func, Func, … 8 Func boolFunc = () => true; Func intFunc = (x) => x intFunc = (x) => x < 10; if (boolFunc() && intFunc(5)) Console.WriteLine("5 < 10"); Console.WriteLine("5 < 10");

Delegates – ExampleDelegates – Example 9 List towns = new List () { "Sofia", "Plovdiv", "Varna", "Sopot", "Silistra" "Sofia", "Plovdiv", "Varna", "Sopot", "Silistra"}; List townsWithS = towns.FindAll(delegate(string town) towns.FindAll(delegate(string town) { return town.StartsWith("S"); return town.StartsWith("S"); }); }); // A short form of the above (with lambda expression) List townsWithS = towns.FindAll((town) => town.StartsWith("S")); towns.FindAll((town) => town.StartsWith("S")); foreach (string town in townsWithS) { Console.WriteLine(town); Console.WriteLine(town);}

Live Demo

 Action - void delegate with parameter T  Func - result delegate returning T 11 Action act = (number) => { Console.WrileLine(number); } Console.WrileLine(number); } act(10); // logs 10 Func greet = (name, age) => { return " Name: " + name + " Age: " + age; return " Name: " + name + " Age: " + age;} Console.WriteLine(greet( "Ivaylo", 10));

Action and Func Action and Func Live Demo

 LINQ is a set of extensions to.NET Framework  Encompasses language-integrated query, set, and transform operations  Consistent manner to obtain and manipulate "data" in the broad sense of the term  Query expressions can be defined directly within the C# programming language  Used to interact with numerous data types  Converted to expression trees at compile time and evaluated at runtime 14

15 LINQ enabled data sources LINQ to Objects Objects LINQ to XML XML LINQ enabled ADO.NET LINQ to DataSets LINQ to SQL LINQ to Entities Relational Data Others Others … C# VB.NET.NET Language-Integrated Query (LINQ)

16 string[] games = {"Morrowind", "BioShock","Half Life", "The Darkness","Daxter", "System Shock 2"}; "The Darkness","Daxter", "System Shock 2"}; // Build a query expression using extension methods // granted to the Array via the Enumerable type var subset = games.Where(game => game.Length > 6). OrderBy(game => game).Select(game => game); OrderBy(game => game).Select(game => game); foreach (var game in subset) Console.WriteLine(game); Console.WriteLine(game);Console.WriteLine();

 The previous example can be adapted to work with a generic list  List, LinkedList, Queue, Stack, HashSet, etc. 17 List books = new List () { "LINQ in Action", "LINQ in Action", "LINQ for Fun", "LINQ for Fun", "Extreme LINQ" }; "Extreme LINQ" }; var titles = books.Where(book => book.Contains("Action"));.Where(book => book.Contains("Action"));

 Although System.String may not be perceived as a collection at first sight  It actually is a collection, because it implements IEnumerable  It actually is a collection, because it implements IEnumerable  String objects can be queried with LINQ to Objects, like any other collection 18 var count = "Non-letter characters in this string: 8".Where(c => !Char.IsLetter(c)).Where(c => !Char.IsLetter(c)).Count();.Count();Console.WriteLine(count); // The result is: 8

 Where()  Searches by given condition  First()/FirstOrDefault()  Gets the first matched element  Last()/LastOrDefault()  Gets the last matched element  Select()/Cast()  Makes projection (conversion) to another type  OrderBy()/ThenBy()/OrderByDescending()  Orders a collection 19

 Any()  Checks if any element matches a condition  All()  Checks if all element matches a condition  ToArray()/ToList()/AsEnumerable()  Converts the collection type  Reverse()  Reverses a collection 20

 Average()  Calculates the average value of a collection  Count()  Counts the elements in a collection  Max()  Determines the maximum value in a collection  Sum()  Sums the values in a collection 21

 Count( )  Max() 22 double[] temperatures = {28.0, 19.5, 32.3, 33.6, 26.5, 29.7}; {28.0, 19.5, 32.3, 33.6, 26.5, 29.7}; int highTempCount = temperatures.Count(p => p > 30); Console.WriteLine(highTempCount); // The result is: 2 double[] temperatures = {28.0, 19.5, 32.3, 33.6, 26.5, 29.7}; {28.0, 19.5, 32.3, 33.6, 26.5, 29.7}; double maxTemp = temperatures.Max(); Console.WriteLine(maxTemp); // The result is: 33.6

Live Demo

Questions?

 C# Telerik Academy  csharpfundamentals.telerik.com csharpfundamentals.telerik.com  Telerik Software Academy  academy.telerik.com academy.telerik.com  Telerik Facebook  facebook.com/TelerikAcademy facebook.com/TelerikAcademy  Telerik Software Academy Forums  forums.academy.telerik.com forums.academy.telerik.com