LINQ: Language-Integrated Queries (To be included in C # 3.0) Technology developed by Anders Hejlsberg & friends at Microsoft (2005) Presented by Tal Cohen.

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
LINQ and Collections An introduction to LINQ and Collections.
Michael Pizzo Software Architect Data Programmability Microsoft Corporation.
A little bit on Class-Based OO Languages CS153: Compilers Greg Morrisett.
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.
Compiler Construction
ASP.NET 3.5 New Features. 2 Agenda What's New in.NET Framework 3.5? Visual Studio 2008 Enhancements LINQ (Language Integrated Query) New ASP.NET Server.
C# 3.0 & LINQ Raimond Brookman – IT Architect
LinqToSharePoint SandBoxed Solution Shakir Majeed Khan
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
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.
Functional programming: LISP Originally developed for symbolic computing First interactive, interpreted language Dynamic typing: values have types, variables.
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.
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.
Extension Methods Programming in C# Extension Methods CSE Prof. Roger Crawfis.
LINQ, An IntroLINQ, An Intro Florin−Tudor Cristea, Microsoft Student Partner.
Eric Vogel Software Developer A.J. Boggs & Company.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 11 th Lecture Pavel Ježek
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# 3.0 and.NET 3.5: A Brief Overview Pavel Ježek.
Delegates and lambda functions Jim Warren, COMPSCI 280 S Enterprise Software Development.
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.
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.
LINQ and C# 3.0 Mads Torgersen Program Manager for the C# Language Microsoft Corporation.
LINQ: It’s Not Your Father’s Data Access Denny Boynton Anheuser-Busch Companies.
The.NET Language Integrated Query Project Anders Hejlsberg TLN306 Technical Fellow Microsoft Corporation.
Neal Stublen How does XMLReader work?  XmlReader.Read() Advances to next node XmlReader properties access node name, value, attributes,
2008.NET iSDC & RONUA Workshop, November 10 th Mark Blomsma Software architect Develop-One.
Hoang Anh Viet Hà Nội University of Technology Chapter 1. Introduction to C# Programming.
8 1 Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
C# 2.0 and Future Directions Anders Hejlsberg Technical Fellow Microsoft Corporation.
Language Integrated Query (LINQ). Data Access Programming Challenges Developers must learn data store-specific query syntax Multiple, disparate data stores.
C#: Future Directions in Language Innovation Anders Hejlsberg TLN307 Technical Fellow Microsoft Corporation.
Object Oriented Programming Generic Collections and LINQ Dr. Mike Spann
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 10 th Lecture Pavel Ježek
Satisfy Your Technical Curiosity C# 3.0 Raj Pai Group Program Manager Microsoft Corporation
IAP C# 2011 Lecture 2: Delegates, Lambdas, LINQ Geza Kovacs.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
LINQ Language Integrated Query LINQ1. LINQ: Why and what? Problem Many data sources: Relational databases, XML, in-memory data structures, objects, etc.
Ken Casada Developer Evangelist Microsoft Switzerland
LINQ and Lambda Expressions Telerik Software Academy LINQ Overview.
Компоненти за работа с DB в.NET Toolbox. Chart //populate dataset with some demo data.. DataSet dataSet = new DataSet(); DataTable dt = new DataTable();
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Building Web Applications with Microsoft ASP
Part 1: Overview of LINQ Intro to LINQ Presenter: PhuongNQK.
Tech·Ed North America /18/2018 2:05 PM
Language Integrated Query: (LINQ) An introduction
LINQ  LINQ – Language INtegrated Query  ( заявки вградени в езика )
Upgrading Your C# Programming Skills to Be a More Effective Developer
Microsoft .NET 3. Language Innovations Pan Wuming 2017.
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
Advanced .NET Programming I 6th Lecture
CPSC-310 Database Systems
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
Language Integrated Query (LINQ)
Language Integrated Query (LINQ)
LINQ & ADO.NET Entity Framework
LINQ - 2 Ravi Kumar C++/C# Team.
Advanced .NET Programming I 7th Lecture
Advanced .NET Programming I 6th Lecture
Chengyu Sun California State University, Los Angeles
CS4540 Special Topics in Web Development LINQ to Objects
Presentation transcript:

LINQ: Language-Integrated Queries (To be included in C # 3.0) Technology developed by Anders Hejlsberg & friends at Microsoft (2005) Presented by Tal Cohen

2 LINQ A C # language extension: –Use SQL-like syntax in C #. Outline: –Examples –Understanding the witchcraft Delegate functions Lambda expressions Type inference Anonymous types Extension methods Expression trees

3 Searching in Collections Begin with a simple array of, say, Customers. Customer[] customers = new Customer[30]; customers[0] = new Customer(…); … customers[29] = new Customer(…);

4 Searching in Collections: The Old Way Find the names of all London customers: List londoners = new List (); foreach (Customer c in customers) { if (c.City == “London”) { londoners.add(c.Name); }

5 Searching in Collections: The LINQ Way string[] londoners = from c in customers where c.City == “London” select c.Name; Declarative! SQL-like! No loops! Returns a simple array!

6 LINQ: How Does It Work? LINQ syntax = shorthand for method invocation. “ Translation maps ”

7 Syntax Translation Example string[] londoners = from c in customers where c.City == “London” select c.Name; string[] londoners = customers. Where( expression ). Select( expression );

8 Translating Expressions Problem: Translating “ c.City == “London” ” to an expression e, such that Where( e ) is valid?

9 Expressions == Methods? Where() wants a Boolean method. The method acts as a filter. Likewise for Select() : a translation method.

10 C # Delegates C # delegates: method pointers. class Demo { delegate void Foo(); void Bar() { … do something … }; void Test() { Foo myDelegate = new Foo(Bar); // “pointer” to Bar() myDelegate(); // invoke }

11 Delegates as Arguments Delegates can be passed as arguments. –Event handlers, jobs for threads, etc. class Demo { void Job() { … the job to carry out … }; void Test() { Thread worker = new Thread( new ThreadStart(Job)); worker.start(); }

12 Anonymous Methods Nameless methods = on-the-fly delegates: class Demo { delegate void Foo(); void Test() { Foo myDelegate = delegate() { … do something … }; myDelegate(); // invoke }

13 Syntax Translation Example string[] londoners = from c in customers where c.City == “London” select c.Name; string[] londoners = customers. Where(delegate(Customer c) { return c.City == “London”; }). Select(delegate(Customer c) { return c.Name });

14 Well, Not Really. Where(), etc. accept delegate methods. But LINQ creates lambda expressions. Seamless conversion.

15 Syntax Translation Example string[] londoners = from c in customers where c.City == “London” select c.Name; string[] londoners = customers. Where(c => c.City == “London”). Select(c => c.Name);

16 Lambda Expressions Lambda expression syntax: (argumentList) => expression oneArgument => expression Arguments optionally typed. –Type inference mechanism. –More on that later … Shades of ML …

17 Where ’ s Where() ? We invoked Where() on Customers[]. On the resulting Customers[], we invoked Select(). New methods for arrays!?

18 Extension Methods class Utils { public static firstChar(this string s) { return s.charAt(0); } So far, just a simple static method. Can be used like any other.

19 Extension Methods But now … Using Utils; class Demo { void Foo() { string s = “Hello”; Console.WriteLine(s.firstChar()); }

20 Extension Methods Static methods that seem to extend existing types. Where(), Select(), etc. extend IEnumerable. –Defined in System.Query. Applicable to one-dimensional array types.

21 Query Your Own Types! LINQ can be applied to any type. Just implement Where(), Select(), etc.

22 LINQ and Relational Data Let ’ s obtain a DB-table type, and query it. DbCustomers c = new DbCustomers(“my.mdb”); string[] londoners = from c in customers where c.City == “London” select c.Name;

23 This Makes No Sense! But … Where() applies the filter to every record. … on the client! SELECT * FROM CUSTOMERS, and filter with a simple loop!?

24 Back To Lambda Expressions Lambda expressions can be converted to anonymous methods. Can also be converted to expression trees. –A run-time representation of the syntax tree.

25 Example … Our code yields: string[] londoners = customers. Where(c => c.City == “London”). Select(c => c.Name); where “ customers ” is of type DbCustomers. No DbCustomers.Where(delegate(Customer c)) method exists. However: DbCustomers.Where( Expression > xt)

26 Expression Trees A data type. Represents lambda expressions at runtime. Used it to generate SQL at runtime. –Guaranteed to be valid.

Relational Algebra: Joins, Projections

28 Multiple Generators (Cartesian Product / Join) OrderData[] od = from c in customers where c.City == “London” from o in c.Orders where o.OrderDate.Year == 2005 select new OrderData(c.Name, o.OrderId, o.Total); OrderData[] od = customers. Where(c => c.City == “London”). SelectMany(c => c.Orders. Where(o => o.OrderDate.Year == 2005). Select(o => new OrderData(c.Name, o.OrderId, o.Total)) );

29 Projections Using LINQ ’ s select : from c in customers where c.City == “London” select new AddressBookEntry(c.Name, c.Phone);

30 Pre-Defined Types Only? But … The projection type (e.g., AddressBookEntry) must be pre- defined!

31 Ad-Hoc Types new { [ name 1 =] expr 1, …, [ name n =] expr n } Type implied by types of exprs. Example: from c in customers where c.City == “London” select new { c.Name, c.Phone }; If name is not specified, and expr is either property or x.property, then property ’ s name will be used. Must not be null -typed.

32 Ad-Hoc Types are Nameless How do we store the result? ??? q = from … select new {…}; The ad-hoc type is nameless! Can’t use Object –Can’t downcast to access the properties.

33 Auto-Typed Variables var x = 7; // x will be of type int var q = from … select new {…}; // q will be an array of the anonymous type Console.WriteLine(q[0].Name); Local variables only.

Extra

35 Relational Data in the OO World? “ Regular ” LINQ queries yields “ rectangular ” data. e.g., var od = from c in customers where c.City == “London” from o in c.Orders where o.OrderDate.Year == 2005 select new { c.Name, o.OrderId, o.Total }; = multiple lines per customer.

36 Relational Data in the OO World? Joe Average Joe Average Joe Average John Smith John Smith Miss Piggy Kermit Kermit

37 OO Data in the OO World! Nested queries: var od = from c in customers where c.City == “London” select new { c.Name, Orders = from o in c.Orders where o.OrderDate.Year == 2005 select { o.OrderId, o.Total } };

38 OO Data in the OO World! Joe Average John Smith Miss Piggy Kermit

39 Ad-Hoc Type Equality Two ad-hoc type expressions that have the same ordered set of property names and types share the same ad-hoc type. var p1 = new { Name = “Moo”, Age = 12 }; var p2 = new { Name = “Elk”, Age = 17 }; p1 = p2;

40 Expression Tree Generation Expression > exprLambda = x => (x & 1) == 0; ParameterExpression xParam = Expression.Parameter(typeof(int), "x"); Expression > exprLambda = Expression.Lambda >( Expression.EQ( Expression.BitAnd( xParam, Expression.Constant(1)), Expression.Constant(0)), xParam);

41 Some LINQ Examples from m in typeof(string).getMethods select m.Name; Clone Compare Format CopyTo Copy IndexOf Insert Substring … String[]

42 Some LINQ Examples from m in typeof(string).getMethods where !m.IsStatic select m.Name; Clone Compare CopyTo Copy IndexOf Insert Substring … String[]

43 Some LINQ Examples from m in typeof(string).getMethods where !m.IsStatic orderby m.name select m.Name; Clone Compare Copy CopyTo IndexOf Insert Substring … String[]

44 Some LINQ Examples from m in typeof(string).getMethods where !m.IsStatic orderby m.name select m.Name groupby m.name; Key = Clone Key = Compare Key = Copy Key = CopyTo Key = IndexOf Key = Insert Key = Substring … KeyGroupPairs[] Group = … …

45 Some LINQ Examples from m in typeof(string).getMethods where !m.IsStatic orderby m.name select m.Name groupby m.name into g select new { Method = g.Key, Overloads = g.Group.Count }; Name = Clone Name = Compare Name = Copy Name = CopyTo Name = IndexOf Name = Insert Name = Substring … var [] Overloads = 1 Overloads = 2 Overloads = 1 Overloads = 5 Overloads = 3 Overloads = 6 …

46 Updates with LINQ? Future feature: updating capabilities. from c in customers where c.City == “Peking” set c.City = “Beijing”; ??

47 DLINQ ADO.NET ’ s next-generation. Among other features: a database-to- classes utility. –Class per DB table. –Property per DB column. –Foreign keys, etc. reflected in the classes. Result: valid table/field names in the SQL.

48 DLINQ – Roll Your Own You can also define your own O/R mapping. By adding attributes (metadata) to classes/fields. Runtime error potential.

49 Updates with DLINQ DLINQ-generated classes include a change-tracking / DB updating mechanism. –a-la EJBs.

50 XLINQ Same idea, for searching in XML data.

51 Extension Methods + Boxing … delegate void Proc(); static class TestExtensions { static public void Times(this Int32 n, Proc proc) { for (int i = 1; i <= n; i++( proc(); } } Which allows you to write: 13.Times(() => Console.Write("X"));