Extension Methods, Anonymous Types LINQ Query Keywords, Lambda Expressions Svetlin Nakov Telerik Corporation www.telerik.com.

Slides:



Advertisements
Similar presentations
Developer Knowledge Sharing Eric Sun Dec, What programming language did you learn in school and since then? Now, its time to refresh …
Advertisements

The Microsoft Technical Roadshow 2007 Language Enhancements and LINQ Daniel Moth Developer & Platform Group Microsoft Ltd
Intro to Scala Lists. Scala Lists are always immutable. This means that a list in Scala, once created, will remain the same.
Lists, Stacks, Queues Svetlin Nakov Telerik Corporation
Generics, Lists, Interfaces
Dictionaries, Hash Tables, Collisions Resolution, Sets Svetlin Nakov Telerik Corporation
Execute Blocks of Code Multiple Times Svetlin Nakov Telerik Corporation
LINQ and Collections An introduction to LINQ and Collections.
Execute Blocks of Code Multiple Times Telerik Software Academy C# Fundamentals – Part 1.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
CSCI 160 Midterm Review Rasanjalee DM.
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
Strings An extension of types A class that encompasses a character array and provides many useful behaviors Chapter 9 Strings are IMMUTABLE.
.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.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
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.
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.
Subroutines in Computer Programming Svetlin Nakov Telerik Corporation
LINQ, An IntroLINQ, An Intro Florin−Tudor Cristea, Microsoft Student Partner.
Eric Vogel Software Developer A.J. Boggs & Company.
Subroutines in Computer Programming Svetlin Nakov Telerik Corporation
Extension Methods, Lambda Expressions, LINQ Operators, Expressions, Projections, Aggregations Extension Methods, Lambda Expressions, LINQ Operators, Expressions,
Characters The data type char represents a single character in Java. –Character values are written as a symbol: ‘a’, ‘)’, ‘%’, ‘A’, etc. –A char value.
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.
Neal Stublen How does XMLReader work?  XmlReader.Read() Advances to next node XmlReader properties access node name, value, attributes,
Hoang Anh Viet Hà Nội University of Technology Chapter 1. Introduction to C# Programming.
Built-in Data Structures in Python An Introduction.
Chapter 9: Perl Programming Practical Extraction and Report Language Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition.
 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.
Arrays, Lists, Stacks, Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
Coding Bat: Ends in ly Given a string of even length, return a string made of the middle two chars, so the string "string" yields "ri". The string.
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
CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections – Exercises 1 Xiang Lian The University of Texas – Pan American Edinburg,
IAP C# 2011 Lecture 2: Delegates, Lambdas, LINQ Geza Kovacs.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
LINQ Language Integrated Query LINQ1. LINQ: Why and what? Problem Many data sources: Relational databases, XML, in-memory data structures, objects, etc.
Arrays and Lists. What is an Array? Arrays are linear data structures whose elements are referenced with subscripts. Just about all programming languages.
Functional Programming Extension Methods, Lambda Expressions, LINQ SoftUni Team Technical Trainers Software University
LINQ and Lambda Expressions Telerik Software Academy LINQ Overview.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
For Friday Read No quiz Program 6 due. Program 6 Any questions?
Chapter 11.  Large amounts of data are often stored in a database—an organized collection of data.  A database management system (DBMS) provides mechanisms.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Building Web Applications with Microsoft ASP
String and Lists Dr. José M. Reyes Álamo.
Arrays, Lists, Stacks, Queues
Introduction to LINQ and Generic Collections
Lambda Expressions By Val Feldsher.
C# Programming Arrays in C# Declaring Arrays of Different Types Initializing Array Accessing Array Elements Creating User Interfaces Using Windows Standards.
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
6 Delegate and Lambda Expressions
Introduction to LINQ Chapter 11 10/28/2015 Lect 4 CT1411.
Introduction to LINQ Chapter 11.
STL - Algorithms.
String and Lists Dr. José M. Reyes Álamo.
CIS 199 Final Review.
COMPUTER PROGRAMMING SKILLS
LINQ - 2 Ravi Kumar C++/C# Team.
CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections – Exercises UTPA – Fall 2012 This set of slides is revised from lecture.
CS4540 Special Topics in Web Development LINQ to Objects
Presentation transcript:

Extension Methods, Anonymous Types LINQ Query Keywords, Lambda Expressions Svetlin Nakov Telerik Corporation

1. Extension methods 2. Anonymous types 3. Lambda expressions 4. LINQ Query keywords 2

 Once a type is defined and compiled into an assembly its definition is, more or less, final  The only way to update, remove or add new members is to recode and recompile the code  Extension methods allow existing compiled types to gain new functionality  Without recompilation  Without touching the original assembly 4

 Extension methods  Defined in a static class  Defined as static  Use this keyword before its first argument to specify the class to be extended  Extension methods are "attached" to the extended class  Can also be called from statically through the defining static class 5

6 public static class Extensions { public static int WordCount(this string str) public static int WordCount(this string str) { return str.Split(new char[] { ' ', '.', '?' }, return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length; StringSplitOptions.RemoveEmptyEntries).Length; }}... static void Main() { string s = "Hello Extension Methods"; string s = "Hello Extension Methods"; int i = s.WordCount(); int i = s.WordCount(); Console.WriteLine(i); Console.WriteLine(i);}

7 public static void IncreaseWidth( this IList list, int amount) this IList list, int amount){ for (int i = 0; i < list.Count; i++) for (int i = 0; i < list.Count; i++) { list[i] += amount; list[i] += amount; }}... static void Main() { List ints = List ints = new List { 1, 2, 3, 4, 5 }; new List { 1, 2, 3, 4, 5 }; ints.IncreaseWidth(5); // 6, 7, 8, 9, 10 ints.IncreaseWidth(5); // 6, 7, 8, 9, 10}

Live Demo

 Anonymous types  Encapsulate a set of read-only properties and their value into a single object  No need to explicitly define a type first  To define an anonymous type  Use of the new var keyword in conjunction with the object initialization syntax 10 var point = new { X = 3, Y = 5 };

 At compile time, the C# compiler will autogenerate an uniquely named class  The class name is not visible from C#  Using implicit typing ( var keyword) is mandatory 11 // Use an anonymous type representing a car var myCar = new { Color = "Red", Brand = "BMW", Speed = 180 }; new { Color = "Red", Brand = "BMW", Speed = 180 }; Console.WriteLine("My car is a {0} {1}.", myCar.Color, myCar.Brand); myCar.Color, myCar.Brand);

 Anonymous types are reference types directly derived from System.Object  Have overridden version of Equals(), GetHashCode(), and ToString()  Do not have == and != operators overloaded 12 var p = new { X = 3, Y = 5 }; var q = new { X = 3, Y = 5 }; Console.WriteLine(p == q); // false Console.WriteLine(p.Equals(q)); // true

 You can define and use arrays of anonymous types through the following syntax: 13 var arr = new[] { new { X = 3, Y = 5 }, new { X = 1, Y = 2 }, new { X = 0, Y = 7 } }; new { X = 1, Y = 2 }, new { X = 0, Y = 7 } }; foreach (var item in arr) { Console.WriteLine("({0}, {1})", Console.WriteLine("({0}, {1})", item.X, item.Y); item.X, item.Y);}

Live Demo

 A lambda expression is an anonymous function containing expressions and statements  Used to create delegates or expression tree types  All lambda expressions use the lambda operator =>, which is read as "goes to"  The left side of the lambda operator specifies the input parameters  The right side holds the expression or statement 17

 Usually used with collection extension methods like FindAll() and RemoveAll() 18 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

19 var pets = new Pet[] { new Pet { Name="Sharo", Age=8 }, new Pet { Name="Sharo", Age=8 }, new Pet { Name="Rex", Age=4 }, new Pet { Name="Rex", Age=4 }, new Pet { Name="Strela", Age=1 }, new Pet { Name="Strela", Age=1 }, new Pet { Name="Bora", Age=3 } new Pet { Name="Bora", Age=3 }}; var sortedPets = pets.OrderBy(pet => pet.Age); foreach (Pet pet in sortedPets) { Console.WriteLine("{0} -> {1}", Console.WriteLine("{0} -> {1}", pet.Name, pet.Age); pet.Name, pet.Age);}

 Lambda code expressions: 20 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, … 21 Func boolFunc = () => true; Func intFunc = (x) => x intFunc = (x) => x < 10; if (boolFunc() && intFunc(5)) Console.WriteLine("5 < 10"); Console.WriteLine("5 < 10");

Live Demo

 Language Integrated Query (LINQ) query keywords  from – specifies data source and range variable  where – filters source elements  select – specifies the type and shape that the elements in the returned sequence  group – groups query results according to a specified key value  orderby – sorts query results in ascending or descending order 23

 select, from and where clauses: 24 int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var querySmallNums = from num in numbers from num in numbers where num < 5 where num < 5 select num; select num; foreach (var num in querySmallNums) { Console.Write(num.ToString() + " "); Console.Write(num.ToString() + " ");} // The result is

 Nested queries: 25 string[] towns = { "Sofia", "Varna", "Pleven", "Ruse", "Bourgas" }; { "Sofia", "Varna", "Pleven", "Ruse", "Bourgas" }; var townPairs = from t1 in towns from t1 in towns from t2 in towns from t2 in towns select new { T1 = t1, T2 = t2 }; select new { T1 = t1, T2 = t2 }; foreach (var townPair in townPairs) { Console.WriteLine("({0}, {1})", Console.WriteLine("({0}, {1})", townPair.T1, townPair.T2); townPair.T1, townPair.T2);}

 Sorting with оrderby : 26 string[] fruits = { "cherry", "apple", "blueberry", "banana" }; { "cherry", "apple", "blueberry", "banana" }; // Sort in ascending sort var fruitsAscending = from fruit in fruits from fruit in fruits orderby fruit orderby fruit select fruit; select fruit; foreach (string fruit in fruitsAscending) { Console.WriteLine(fruit); Console.WriteLine(fruit);}

Live Demo

Questions?

1. Implement an extension method Substring(int index, int length) for the class StringBuilder that returns new StringBuilder and has the same functionality as Substring in the class String. 2. Implement a set of extension methods for IEnumerable that implement the following group functions: sum, product, min, max, average. 3. Write a method that from a given array of students finds all students whose first name is before its last name alphabetically. Use LINQ query operators. 4. Write a LINQ query that finds the first name and last name of all students with age between 18 and

5. Using the extension methods OrderBy() and ThenBy() with lambda expressions sort the students by first name and last name in descending order. Rewrite the same with LINQ. 6. Write a program that prints from given array of integers all numbers that are divisible by 7 and 3. Use the built-in extension methods and lambda expressions. Rewrite the same with LINQ. 7. Write extension method to the String class that capitalizes the first letter of each word. Use the method TextInfo.ToTitleCase(). 30