Extension Methods, Lambda Expressions, LINQ Operators, Expressions, Projections, Aggregations Extension Methods, Lambda Expressions, LINQ Operators, Expressions,

  • View
    219

  • Download
    3

Embed Size (px)

Transcript

LINQ and LINQ-to-SQL

Language Integrated Query in .NET (LINQ) Extension Methods, Lambda Expressions, LINQ Operators, Expressions, Projections, AggregationsSvetlin Nakov

Telerik Corporation

www.telerik.com

http://schoolacademy.telerik.com*(c) 2008 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*1##Table of ContentsExtension MethodsAnonymous Types Lambda ExpressionsLINQ Building BlocksQuery Operators and ExpressionsQuery Expression TreesLINQ to Objects: Querying CollectionsProjection, Conversion, AggregationSorting, Grouping, Joins, Nested Queries2

*(c) 2008 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*2##Extension Methods

*(c) 2008 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*3##Extension MethodsOnce a type is defined and compiled into an assembly its definition is, more or less, finalThe only way to update, remove or add new members is to recode and recompile the codeExtension methods allow existing compiled types to gain new functionalityWithout recompilationWithout touching the original assembly4

Defining Extension MethodsExtension methodsDefined in a static classDefined as staticUse this keyword before its first to specify the class to be extendedExtension methods are "attached" to the extended classCan also be called from statically through the defining static class5Extension Methods Examples6public static class Extensions{ public static int WordCount(this string str) { return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length; }} ...static void Main(){ string s = "Hello Extension Methods"; int i = s.WordCount(); Console.WriteLine(i);}Extension Methods Examples (2)7public static void IncreaseWidth( this IList list, int amount){ for (int i = 0; i < list.Count; i++) { list[i] += amount; }}...static void Main(){ List ints = new List { 1, 2, 3, 4, 5 }; ints.IncreaseWidth(5); // 6, 7, 8, 9, 10}Extension MethodsLive Demo

*(c) 2008 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*8##Anonymous Types

*(c) 2008 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*9##Anonymous TypesAnonymous typesEncapsulate a set of read-only properties and their value into a single objectNo need to explicitly define a type firstTo define an anonymous typeUse of the new var keyword in conjunction with the object initialization syntax10var point = new { X = 3, Y = 5 };Anonymous Types ExampleAt compile time, the C# compiler will autogenerate an uniquely named classThe class name is not visible from C#Using implicit typing (var keyword) is mandatory11// Use an anonymous type representing a carvar myCar = new { Color = "Red", Brand = "BMW", Speed = 180 };Console.WriteLine("My car is a {0} {1}.", myCar.Color, myCar.Brand);Anonymous Types PropertiesAnonymous types are reference types directly derived from System.ObjectHave overridden version of Equals(), GetHashCode(), and ToString()Do not have == and != operators overloaded12var p = new { X = 3, Y = 5 };var q = new { X = 3, Y = 5 };Console.WriteLine(p == q); // falseConsole.WriteLine(p.Equals(q)); // trueArrays of Anonymous TypesYou can define and use arrays of anonymous types through the following syntax:13var arr = new[] { new { X = 3, Y = 5 }, new { X = 1, Y = 2 }, new { X = 0, Y = 7 }};foreach (var item in arr){ Console.WriteLine("({0}, {1})", item.X, item.Y);}Anonymous TypesLive Demo

*(c) 2008 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*14##Lambda Expressions

*(c) 2008 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*15##Lambda ExpressionsA lambda expression is an anonymous function containing expressions and statementsUsed to create delegates or expression tree typesAll lambda expressions use the lambda operator =>, which is read as "goes to"The left side of the lambda operator specifies the input parametersThe right side holds the expression or statement 16Lambda Expressions ExamplesUsually used with collection extension methods like FindAll() and Count()17List list = new List() { 1, 2, 3, 4 };List evenNumbers = list.FindAll(x => (x % 2) == 0);foreach (var num in evenNumbers){ Console.Write("{0} ", num);}Console.WriteLine();// 2 4

list.RemoveAll(x => x > 3); // 1 2 3Sorting with Lambda Expression18var pets = new Pet[]{ new Pet { Name="Sharo", Age=8 }, new Pet { Name="Rex", Age=4 }, new Pet { Name="Strela", Age=1 }, new Pet { Name="Bora", Age=3 }};var sortedPets = pets.OrderBy(pet => pet.Age);foreach (Pet pet in sortedPets){ Console.WriteLine("{0} -> {1}", pet.Name, pet.Age);}Lambda Code ExpressionsLambda code expressions:19List list = new List() { 20, 1, 4, 8, 9, 44 };

// Process each argument with code statementsList evenNumbers = list.FindAll((i) => { Console.WriteLine("value of i is: {0}", i); return (i % 2) == 0; });

Console.WriteLine("Your even numbers are:");foreach (int even in evenNumbers) Console.Write("{0}\t", even);Delegates Holding Lambda FunctionsLambda functions can be stored in variables of type delegateDelegates are typed references to functionsStandard function delegates in .NET:Func, Func, Func,

20Func boolFunc = () => true;Func intFunc = (x) => x < 10;if (boolFunc() && intFunc(5)) Console.WriteLine("5 < 10");Lambda ExpressionsLive Demo

*(c) 2008 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*21##LINQ and Query Keywords

*(c) 2008 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*22##LINQ and Query KeywordsLanguage Integrated Query (LINQ) query keywordsfrom specifies data source and range variablewhere filters source elementsselect specifies the type and shape that the elements in the returned sequencegroup groups query results according to a specified key valueorderby sorts query results in ascending or descending order23Query Keywords Examplesselect, from and where clauses:24int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

var querySmallNums = from num in numbers where num < 5 select num;

foreach (var num in querySmallNums){ Console.Write(num.ToString() + " ");}// The result is 4 1 3 2 0

Query Keywords Examples (2)Nested queries:25string[] towns = { "Sofia", "Varna", "Pleven", "Ruse", "Bourgas" };

var townPairs = from t1 in towns from t2 in towns select new { T1 = t1, T2 = t2 };

foreach (var townPair in townPairs){ Console.WriteLine("({0}, {1})", townPair.T1, townPair.T2);}

Query Keywords Examples (3)Sorting with rderby:26string[] fruits = { "cherry", "apple", "blueberry", "banana" };

// Sort in ascending sortvar fruitsAscending = from fruit in fruits orderby fruit select fruit;

foreach (string fruit in fruitsAscending){ Console.WriteLine(fruit);}

LINQ Query KeywordsLive Demo

*(c) 2008 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*27##

LINQ Building Blocks

*(c) 2008 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*28##LINQ Building BlocksSoftware developers spend a lot of time to obtain and manipulate dataData can be stored inCollectionsDatabasesXML documentsetc...As of .NET 3.5 developers can use LINQ a simplified approach to data manipulation29

LINQ Building Blocks (2)LINQ is a set of extensions to .NET FrameworkEncompasses language-integrated query, set, and transform operationsConsistent manner to obtain and manipulate "data" in the broad sense of the termQuery expressions can be defined directly within the C# programming languageUsed to interact with numerous data typesConverted to expression trees at compile time and evaluated at runtime30LINQ Building Blocks (3)LINQ allows query expressions to manipulate:Any object implementing IEnumerableCollections of objectsRelational databasesXML documentsThe query expressions are based on numerous SQL-like query operatorsIntentionally designed to look and feel very similar to SQL expressions31LINQ Building Blocks (4) "LINQ" is the term used to describe this overall approach to data accessLINQ to ObjectsLINQ over objects implementing IEnumerableLINQ to SQL and LINQ to Entities implement LINQ over relational dataLINQ to DataSet is a superset of LINQ to SQLLINQ to XML is LINQ over XML documents32LINQ to *33LINQ enabled data sources

LINQ to ObjectsObjects

LINQto XML

XMLLINQ enabled ADO.NET

LINQ to DataSets

LINQto SQL

LINQ toEntitiesRelational Data

Others

C#

VB.NET

.NET Language-Integrated Query (LINQ)Query OperationsAll LINQ query operations consist of three distinct actions:Obtain the data sourceCreate the queryExecute the query34

LINQ Sequences*(c) 2008 National Academy for Software Development - http://academy