LINQ, An IntroLINQ, An Intro Florin−Tudor Cristea, Microsoft Student Partner.

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 to objects. Datenmodell Zugriffsklasse Einfache Abfrage IEnumerable booksList = SampleDataAccess.DBooks.Select(b => b); Select(...) Book => object.
LINQ (Language Integrated Query)
2 C# 1.0 C# 2.0 C# 3.0 Komponensek felügyelt környezetben • Property, delegate, event Típusbiztosabb, hatékonyabb nyelv • Generikus típusok, yield return.
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.
Chapter 5 Types. 5-2 Topics in this Chapter Values vs. Variables Types vs. Representations Type Definition Operators Type Generators SQL Facilities.
The Weakest LINQ: Querying the AutoCAD® Database James E. Johnson Software Developer CaptiveAire Systems Inc.
DryadLINQ A System for General-Purpose Distributed Data-Parallel Computing Yuan Yu, Michael Isard, Dennis Fetterly, Mihai Budiu, Úlfar Erlingsson, Pradeep.
C# 3.0 & LINQ Raimond Brookman – IT Architect
Damien Guard (BSc, MBCS) Guernsey Software Developer Forum Language Integrated Query:
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.
PARALLEL PROGRAMMING ABSTRACTIONS 6/16/2010 Parallel Programming Abstractions 1.
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.
Slides from Gang Luo, Xuting Zhao and Damien Guard
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 11 th Lecture Pavel Ježek
Lambdas and Streams. Functional interfaces Functional interfaces are also known as single abstract method (SAM) interfaces. Package java.util.function.
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
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 LINQ Lecture # 19 August Introduction How do you interrogate/manipulate data? What if you could do the work in a type-safe," string-free.
The.NET Language Integrated Query Project Anders Hejlsberg TLN306 Technical Fellow Microsoft Corporation.
 Language Integrated Query  Make query a part of the language  Component of.NET Framework 3.5  Shipped with Visual Studio 2008.
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.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
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
LINQ & PLINQ (Parallel) Language Integrated Query.
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
Linq Overview Vincent GERMAIN. Evolution - Rappel Langage  C# 2.0  C# 3.0 (Local type inference, Lambda expression, Method extension,Anonymous type)
Damien Guard (BSc, MBCS) Guernsey Software Developer Forum Language Integrated Query:
Joel Pobar Language Geek Microsoft DEV320 Improve on C# % Backwards Compatible Language Integrated Query (LINQ)
IAP C# 2011 Lecture 2: Delegates, Lambdas, LINQ Geza Kovacs.
CSE 6331 © Leonidas Fegaras XQuery 1 XQuery Leonidas Fegaras.
LINQ Language Integrated Query LINQ1. LINQ: Why and what? Problem Many data sources: Relational databases, XML, in-memory data structures, objects, etc.
LINQ and Lambda Expressions Telerik Software Academy LINQ Overview.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
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
Part 1: Overview of LINQ Intro to LINQ Presenter: PhuongNQK.
Jim Fawcett CSE681 – Software Modeling and Analysis Fall 2016
Introduction to LINQ and Generic Collections
Jim Fawcett CSE681 – Software Modeling and Analysis Fall 2013
Intro to LINQ Part 2 – Concepts and LINQ to Objects
Language Integrated Query: (LINQ) An introduction
Advanced .NET Programming I 6th Lecture
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
Introduction to LINQ Chapter 11 10/28/2015 Lect 4 CT1411.
Introduction to LINQ Chapter 11.
Statement-Level Control Structures
Chapter 8 Advanced SQL.
XQuery Leonidas Fegaras.
LINQ - 2 Ravi Kumar C++/C# Team.
Advanced .NET Programming I 7th Lecture
CS4540 Special Topics in Web Development LINQ to Objects
Presentation transcript:

LINQ, An IntroLINQ, An Intro Florin−Tudor Cristea, Microsoft Student Partner

Hello, LINQ!Hello, LINQ! Because “Hello, world!” is so out of fashion.

Inspiration sources ~alexandru.stefan/ materiale/ LINQ.pdf en-us/ vcsharp/ aa aspx

Language INtegrated Query

Software is simple. It boils down to two things: code and data. Writing software is not so simple, and one of the major activities it involves is writing code that deals with data.

LINQ could be the missing link—whether this pun is intended is yet to be discovered—between the data world and the world of general-purpose programming languages.

LINQ unifies data access, whatever the source of data, and allows mixing data from different kind of sources. It allows for query and set operations, similar to what SQL statements offer for databases.

LINQ was designed to be used against any type of object or data source and to provide a consistent programming model for doing so.

Once you learn how to use LINQ against an array or a collection, you also know most of the concepts needed to take advantage of LINQ with a database or an XML file.

HelloLINQ.csproj hello linq world Words of length 9 beautiful wonderful Words of length 5 hello world Words of length 4 linq Total number of chars is 32 (an average of 6,4 per word)

Hello, um… language enhancements! “How much wood could a woodchuck chuck if a woodchuck could chuck wood?” or what makes LINQ tick.

Implicitly typed local variables, which permit the types of local variables to be inferred from the expressions used to initialize them.

Object initializers, which ease construction and initialization of objects.

Lambda expressions, an evolution of anonymous methods that provides improved type inference and conversion to both delegate types and expression trees.

Extension methods, which make it possible to extend existing types and constructed types with additional methods. With extension methods, types aren’t extended but look as if they were.

Anonymous types, which are types automatically inferred and created from object initializers.

HelloLE.csproj HelloLEContd.csproj ExtensionMethodsDiscoverability.csproj

LINQ building blocksLINQ building blocks Warning, headsplosions ahead!

static void DisplayProcesses() { var processes = Process.GetProcesses().Where(process => process.WorkingSet64 > 20*1024*1024).OrderByDescending(process => process.WorkingSet64).Select(process => new { process.Id, Name=process.ProcessName }); ObjectDumper.Write(processes); }

sequences query expressions query operators deferred query exec. expression trees

static void DisplayProcesses() { var processes = Process.GetProcesses().Where(process => process.WorkingSet64 > 20*1024*1024).OrderByDescending(process => process.WorkingSet64).Select(process => new { process.Id, Name=process.ProcessName }); ObjectDumper.Write(processes); }

The GetProcesses method of the System.Diagnostics.Process class returns an array of Process objects. This is not surprising and probably wouldn’t be interesting, except that arrays implement the generic IEnumerable interface. This interface, which appeared with.NET 2.0, is key to LINQ. In our particular case, an array of Process objects implements IEnumerable.

The IEnumerable interface is important because Where, OrderByDescending, Select, and other standard query operators used in LINQ queries expect an object of this type as a parameter.

public static IEnumerable Where ( this IEnumerable source, Func predicate) { foreach (TSource element in source) { if (predicate(element)) yield return element; } } // System.Linq.Enumerable

An iterator is an object that allows you to traverse through a collection’s elements. What is named an iterator in.NET is also known as a generator in other languages such as Python, or sometimes a cursor, especially within the context of a database.

An iterator is easy to create: it’s simply a method that returns an enumeration and uses yield return to provide the values. Iterator.csproj

LINQ queries rely heavily on lazy evaluation (deferred query execution). This is one of the most important concepts in LINQ. Without this facility, LINQ would perform very poorly. DeferredQueryExecution.csproj

Query operators are not a language extension per se, but an extension to the.NET FCL. Query operators are a set of extension methods that perform operations in the context of LINQ queries. They are the real elements that make LINQ possible.

static void DisplayProcesses() { var processes = Process.GetProcesses().Where(process => process.WorkingSet64 > 20*1024*1024).OrderByDescending(process => process.WorkingSet64).Select(process => new { process.Id, Name=process.ProcessName }); ObjectDumper.Write(processes); } Call to Where

public static IEnumerable Where ( this IEnumerable source, Func predicate) { foreach (TSource element in source) { if (predicate(element)) yield return element; } } foreach loop Filter source Return elements

Some intermediate operations (such as sorting and grouping) do require the entire source be iterated over. Our OrderByDescending call is an example of this.

We’ve stressed several characteristics of extension methods ( Where, etc.): They work on enumerations. They allow pipelined data processing. They rely on delayed execution. All these features make these methods useful to write queries. This explains why these methods are called query operators.

FamilyQuery operators Filtering OfType, Where Projection Select, SelectMany Partitioning Skip, SkipWhile, Take, TakeWhile Join GroupJoin, Join Concatenation Concat Ordering OrderBy, OrderByDescending, Reverse, ThenBy, ThenByDescending Grouping GroupBy, ToLookup Set Distinct, Except, Intersect, Union Conversion AsEnumerable, AsQueryable, Cast, ToArray, ToDictionary, ToList Equality SequenceEqual Element ElementAt, ElementAtOrDefault, First, FirstOrDefault, Last, LastOrDefault, Single, SingleOrDefault Generation DefaultIfEmpty, Empty, Range, Repeat Quantifiers All, Any, Contains Aggregation Aggregate, Average, Count, LongCount, Max, Min, Sum

var processes = Process.GetProcesses().Where(process => process.WorkingSet64 > 20*1024*1024).OrderByDescending(process => process.WorkingSet64).Select(process => new { process.Id, Name=process.ProcessName });

var processes = from process in Process.GetProcesses() where process.WorkingSet64 > 20*1024*1024 orderby process.WorkingSet64 descending select new { process.Id, Name=process.ProcessName };

The two code pieces are semantically identical. A query expression is convenient declarative shorthand for code you could write manually. Query expressions allow us to use the power of query operators, but with a query-oriented syntax.

When you use a query expression, the compiler automagically translates it into calls to standard query operators.

from id in source { from id in source | join id in source on expr equals expr [ into id ] | let id = expr | where condition | orderby ordering, ordering, … } select expr | group expr by key [ into id query ] Starts with from Zero or more from, join, let, where, or orderby Ends with select or group by Ends with select or group by Optional into continuation Use let to declare temporary variables

Query operatorC# syntax All N/A Any N/A Average N/A Cast Use an explicitly typed range variable, for example: from int i in numbers Count N/A Distinct N/A GroupBy group... by group... by... into... GroupJoin join... in... on... equals... into... Join join... in... on... equals... LongCount N/A Max N/A Min N/A

Query operatorC# syntax OrderByorderby OrderByDescendingorderby... descending Selectselect SelectMany Multiple from clauses Skip N/A SkipWhile N/A Sum N/A Take N/A TakeWhile N/A ThenByorderby...,... ThenByDescendingorderby...,... descending Wherewhere

var authors = from distinctAuthor in ( from book in SampleData.Books where book.Title.Contains("LINQ") from author in book.Authors.Take(1) select author).Distinct() select new {distinctAuthor.FirstName, distinctAuthor.LastName};

var authors = SampleData.Books.Where(book => book.Title.Contains("LINQ")).SelectMany(book => book.Authors.Take(1)).Distinct().Select(author => new {author.FirstName, author.LastName});

As for expression trees... we’ll cover these later (deferred query execution redux, IQueryable, dynamic queries, abracadabra). Maybe.

System.Core.dll System System.Linq System.Linq.Expressions System.Data.DataSetExtensions.dll System.Data System.Data.Linq.dll System.Data.Linq System.Data.Linq.Mapping System.Data.Linq.SqlClient System.Xml.Linq.dll System.Xml.Linq System.Xml.Schema System.Xml.XPath

See y’all next time!