Www.itu.dk Advanced C#, part IV Niels Hallenberg IT University of Copenhagen (With thanks to Peter Sestoft and Kasper Østerbye) BAAAP – Spring 2009.

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

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
The Microsoft Technical Roadshow 2007 Language Enhancements and LINQ Daniel Moth Developer & Platform Group Microsoft Ltd
Deep Dive into LINQ Eran Sharabi.NET Development Team Leader JohnBryce Training
LINQ and Collections An introduction to LINQ and Collections.
Extension Methods, Anonymous Types LINQ Query Keywords, Lambda Expressions Svetlin Nakov Telerik Corporation
C# and LINQ Yuan Yu Microsoft Research Silicon Valley.
Presented by: Andrew Gray 1Introduction to LINQ and Lambda Expressions.
LINQ: Language-Integrated Queries (To be included in C # 3.0) Technology developed by Anders Hejlsberg & friends at Microsoft (2005) Presented by Tal Cohen.
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.
Saturday May 02 PST 4 PM. Saturday May 02 PST 10:00 PM.
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.
PARALLEL PROGRAMMING ABSTRACTIONS 6/16/2010 Parallel Programming Abstractions 1.
LINQ Programming in C# LINQ CSE Prof. Roger Crawfis.
 Introduction  What is LINQ  Syntax  How to Query  Example Program.
The foreach LooptMyn1 The foreach Loop The foreach loop gives an easy way to iterate over arrays. foreach works only on arrays, and will issue an error.
Slides from Gang Luo, Xuting Zhao and Damien Guard
Extension Methods Programming in C# Extension Methods CSE Prof. Roger Crawfis.
LINQ, An IntroLINQ, An Intro Florin−Tudor Cristea, Microsoft Student Partner.
Advanced .NET Programming I 13th Lecture
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 11 th Lecture Pavel Ježek
Microsoft Access DataBase Automated Grading System
Getting familiar with LINQ to Objects Florin−Tudor Cristea, Microsoft Student Partner.
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.
LINQ TO XML Mike Taulty Developer & Platform Group Microsoft UK
@CRMUG Technical Academy Fetch Xml Were can Fetch Xml be used Basic Fetch Xml and using advanced find to build your own Fetch Query Creating Fetch Xml.
Extension Methods, Anonymous Types LINQ Query Keywords, Lambda Expressions Based on material from Telerik Corporation.
Monads Steve Goguen. About Me Web Developer for Allied Building Supply  ASP.NET, SQL Server, LINQ, etc. Website:
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.
Neal Stublen How does XMLReader work?  XmlReader.Read() Advances to next node XmlReader properties access node name, value, attributes,
 Language Integrated Query  Make query a part of the language  Component of.NET Framework 3.5  Shipped with Visual Studio 2008.
LINQ Providers Or why.NET rules, and Java doesn’t Branimir Giurov SofiaDev.org UG Lead, C# MVP Freelance Software Developer
Hoang Anh Viet Hà Nội University of Technology Chapter 1. Introduction to C# Programming.
 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.
1 LinQ Introduction. Outline Goals of LinQ Anatomy of a LinQ query More expression examples LinQ to Objects LinQ to XML LinQ to SQL 2.
C# 2.0 and Future Directions Anders Hejlsberg Technical Fellow Microsoft Corporation.
C#: Future Directions in Language Innovation Anders Hejlsberg TLN307 Technical Fellow Microsoft Corporation.
Applied Linq Putting Linq to work Introducing… Class-A Kennisprovider Microsoft development Training Coaching Alex Thissen Trainer/coach.
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
Inside LINQ to Objects How LINQ to Objects work Inside LINQ1.
Advanced C#, part I Niels Hallenberg IT University of Copenhagen BAAAP – Spring 2009.
Satisfy Your Technical Curiosity C# 3.0 Raj Pai Group Program Manager Microsoft Corporation
CSED101 INTRODUCTION TO COMPUTING SUM TYPE 유환조 Hwanjo Yu.
CIS 200 Test 01 Review. Built-In Types Properties  Exposed “Variables” or accessible values of an object  Can have access controlled via scope modifiers.
IAP C# 2011 Lecture 2: Delegates, Lambdas, LINQ Geza Kovacs.
LINQ Language Integrated Query LINQ1. LINQ: Why and what? Problem Many data sources: Relational databases, XML, in-memory data structures, objects, etc.
Pointers A pointer type variable holds the address of a data object or a function. A pointer can refer to an object of any one data type; it cannot refer.
LINQ and Lambda Expressions Telerik Software Academy LINQ Overview.
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.
Building Web Applications with Microsoft ASP
Part 1: Overview of LINQ Intro to LINQ Presenter: PhuongNQK.
Jim Fawcett CSE681 – Software Modeling and Analysis Fall 2016
Jim Fawcett CSE681 – Software Modeling and Analysis Fall 2013
Lambda Expressions By Val Feldsher.
Intro to LINQ Part 2 – Concepts and LINQ to Objects
Language Integrated Query: (LINQ) An introduction
LiNQ SQL Saturday David Fekke.
Advanced .NET Programming I 6th Lecture
Introduction to LINQ Chapter 11 10/28/2015 Lect 4 CT1411.
Introduction to LINQ Chapter 11.
INFO 344 Web Tools And Development
LINQ - 2 Ravi Kumar C++/C# Team.
Advanced .NET Programming I 7th Lecture
Advanced .NET Programming I 6th Lecture
CS4540 Special Topics in Web Development LINQ to Objects
Presentation transcript:

Advanced C#, part IV Niels Hallenberg IT University of Copenhagen (With thanks to Peter Sestoft and Kasper Østerbye) BAAAP – Spring 2009

Outline Advanced C#, Part IV Basic LINQ –Deferred Queryies

Deferred Query The following query is executed when iterating through the list. var xs = new string[] {"hii", "there", null, "are", "you"}; Console.WriteLine("Before Where() is called."); IEnumerable xs3 = xs.Where(s => s.Length == 3); Console.WriteLine("After Where() is called."); try { foreach (var x in xs3) Console.WriteLine("Processing " + x); } catch (Exception e) { Console.WriteLine("Got exception " + e); } Project example: LINQ04.sln

Deferred Query Another example of a deferred query – where the underlying data source is changed. var intxs = new int[] { 1, 2, 3 }; IEnumerable ints = intxs.Select(i => i); foreach (var i in ints) Console.WriteLine("i = " + i); intxs[1] = 42; Console.WriteLine(" "); foreach (var i in ints) Console.WriteLine("i = " + i); Project example: LINQ04.sln

Deferred Query The IEnumerable extension methods are lazy So a query is executed only – and once every time – the result is demanded: int[] numbers = new int[] { 5, 4, 1, 3, 9 }; int i = 0; var q = from n in numbers select new { n, i = ++i }; foreach (var v in q) Console.WriteLine(v); foreach (var v in q) Console.WriteLine(v); { n = 5, i = 1 } { n = 4, i = 2 } { n = 1, i = 3 } { n = 3, i = 4 } { n = 9, i = 5 } { n = 5, i = 6 } { n = 4, i = 7 } { n = 1, i = 8 } { n = 3, i = 9 } { n = 9, i = 10 }

Translation of group by The query is expanded to from x in xs group x by e xs.GroupBy(x => e)

Extension methods for grouping As list comprehension –Compute ks = distinct([ h(x) | x <- xs ]) –Return [ (k, [ x | x <- xs, h(x)=k ]) | k <- ks ] A grouping is an enumerable with a key: IEnumerable > GroupBy (this IEnumerable xs, Func h) interface IGrouping : IEnumerable { K Key { get; } } var xs = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; var gs = xs.GroupBy(i => i < 5 ? "A" : "B"); foreach (var g in gs) Console.WriteLine("g = (" + g.Key + ",[" + g.toString() + "])"); Project example: LINQ05.sln

Translations of join The query is expanded to from x in xs join y in ys on kx equals ky select e xs.Join(ys, x => kx, y => ky, (x,y) => e) The query is expanded to from x in xs join y in ys on kx equals ky into z select e xs.GroupJoin(ys, x => kx, y => ky, (x,z) => e)

Extension methods for join 1 As list comprehension: [ g(x,y) | x <- xs, y <- ys, fx(x)=fy(y) ] Efficient even on enumerables (I guess): –Make multidictionary fx(x) -> x for all x in xs –For each y in ys compute fy(y), look up matching x values, for each of them yield g(x,y) IEnumerable Join (this IEnumerable xs, IEnumerable ys, Func fx, Func fy, Func g)

Extension methods for join 2 As list comprehension: [ g(x, [y | y <- ys, fx(x)=fy(y) ]) | x <- xs ] IEnumerable GroupJoin (this IEnumerable xs, IEnumerable ys, Func fx, Func fy, Func,V> g)

Order weekday distribution by weekday { Key = Sunday, Count = 95 } { Key = Monday, Count = 52 } { Key = Tuesday, Count = 15 } { Key = Wednesday, Count = 17 } { Key = Thursday, Count = 60 } { Key = Friday, Count = 61 } { Key = Saturday, Count = 18 } var holidayWeekDays = from dt in DateTimeExtensions.holidays.Keys group dt by dt.DayOfWeek into g orderby g.Key select new { g.Key, Count = g.Count() };

Translation of orderby The query is expanded to from x in xs orderby k1, k2,... xs.OrderBy(x => k1).ThenBy(x => k2)....

Extension methods for ordering Order xs by ascending h(x) An ordered enumerable –remembers its previous ordering criteria –supports ordering by further (secondary) criteria while respecting previous criteria IOrderedEnumerable OrderBy (this IEnumerable xs, Func h) IOrderedEnumerable ThenBy (this IOrderedEnumerable xs, Func h)

Expression trees Covers C# expressions except assignment An expression tree can be compiled into SQL A function can be called but not inspected: Func f = x => 3*x; int res = f(7); Expression > t = x => 3*x; An expression tree can be inspected: => x x3 * t = Abstract syntax for lambda x => 3 * x

From lambda to expression tree A lambda may convert to expression tree at assignment to variable, field or parameter bool Where(Expression > p) {…} bool foo = Where(z => z>42); p will be a tree, not a function The tree may be analysed by the Where method => z 42z >

Linq to relational databases For Linq to collections (or in-memory XML), enumerable extension methods are efficient For Linq to relational database, they aren’t Instead, –the query gets rewritten to method calls, as usual –the System.Linq.Data.Table.Where method is Where(Expression > p) –it captures the predicate p as an expression tree and rewrites it to an SQL fragment –same for Select, Join, GroupBy, OrderBy, ThenBy –The DB server executes SQL and returns results Works even if the delegates involve local (client-side) computation, but may be slow

Linq samples in VS2008 Go Help > Samples > CSharpSamples > LinqSamples > SampleQueries Build and run project SampleQueries Shows the SQL generated by Linq to SQL See 101+ Linq to Sql Query Samples If not installed, then first –go Help > Samples > local Samples folder > unzip CSharpSamples.zip –install in Program Files\Microsoft Visual Studio 9.0\Samples\1033\CSharpSamples\