LINQ (Language Integrated Query)

Slides:



Advertisements
Similar presentations
The Microsoft Technical Roadshow 2007 Language Enhancements and LINQ Daniel Moth Developer & Platform Group Microsoft Ltd
Advertisements

LINQ to objects. Datenmodell Zugriffsklasse Einfache Abfrage IEnumerable booksList = SampleDataAccess.DBooks.Select(b => b); Select(...) Book => object.
LINQ Stefan Flöring Department für Informatik Carl von Ossietzky Universität Oldenburg.
Union, Intersection, Difference (subquery) UNION (subquery) produces the union of the two relations. Similarly for INTERSECT, EXCEPT = intersection and.
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.
Zoeken met Sitecore 7 Egbert Wietses pionect.nl.
SQL Introduction Standard language for querying and manipulating data Structured Query Language Many standards out there: SQL92, SQL2, SQL3. Vendors support.
Deep Dive into LINQ Eran Sharabi.NET Development Team Leader JohnBryce Training
LINQ and Collections An introduction to LINQ and Collections.
Michael Pizzo Software Architect Data Programmability Microsoft Corporation.
Extension Methods, Anonymous Types LINQ Query Keywords, Lambda Expressions Svetlin Nakov Telerik Corporation
XML Language Family Detailed Examples Most information contained in these slide comes from: These slides are intended.
C# and LINQ Yuan Yu Microsoft Research Silicon Valley.
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:
Object-Orientation in Query Languages By: Toan Nguyen Class: CS 157A.
Tools of the trade TSQL CIS 407. SQL Server Tools Books on line! Don’t use sql server authentication –Use windows authentication (safer) for developer.
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.
XML files (with LINQ). Introduction to LINQ ( Language Integrated Query ) C#’s new LINQ capabilities allow you to write query expressions that retrieve.
Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.
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
Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer)
LINQ, An IntroLINQ, An Intro Florin−Tudor Cristea, Microsoft Student Partner.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics LINQ to XML: A Brief Overview Pavel Ježek.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 11 th Lecture Pavel Ježek
Getting familiar with LINQ to Objects Florin−Tudor Cristea, Microsoft Student Partner.
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.
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,
 Language Integrated Query  Make query a part of the language  Component of.NET Framework 3.5  Shipped with Visual Studio 2008.
 Although VERY commonly used, arrays have limited capabilities  A List is similar to an array but provides additional functionality, such as dynamic.
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.
IMS 4212: Data Manipulation 1 Dr. Lawrence West, MIS Dept., University of Central Florida Additional Data Manipulation Statements INSERT.
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.
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.
SQL SELECT Getting Data from the Database. Basic Format SELECT, FROM WHERE (=, >, LIKE, IN) ORDER BY ; SELECT LastName, FirstName, Phone, City FROM Customer.
Satisfy Your Technical Curiosity C# 3.0 Raj Pai Group Program Manager Microsoft Corporation
1 MySQL and SQL. 2 Topics  Introducing Relational Databases  Terminology  Managing Databases MySQL and SQL.
Linq Overview Vincent GERMAIN. Evolution - Rappel Langage  C# 2.0  C# 3.0 (Local type inference, Lambda expression, Method extension,Anonymous type)
Structured Query Language SQL Unit 4 Solving Problems with SQL.
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.
LINQ Language Integrated Query LINQ1. LINQ: Why and what? Problem Many data sources: Relational databases, XML, in-memory data structures, objects, etc.
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Functional Programming
How to: SQL By: Sam Loch.
Jim Fawcett CSE681 – Software Modeling and Analysis Fall 2016
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
Chapter 4 Summary Query.
Database systems Lecture 3 – SQL + CRUD
INFO 344 Web Tools And Development
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 (Language Integrated Query)

Übersicht Einleitung zu LINQ LINQ Syntax LINQ to Objects (Übungen) LINQ to XML LINQ to SQL Fragen/Diskussion

Was ist LINQ? Komponente zum Abfragen von Datenquellen Modifizieren und neu erstellen von Daten .Net 3.0 erste Version .Net 3.5 erweitert (anfragemanipulierende Erweiterungsmethoden) .Net 4.0 PLINQ (Parallel LINQ) Standard Data Provider: LINQ to Objects, SQL, DataSets, XML

Vorteile und Nachteile Überprüfung durch Compiler Teilweise spürbar langsamer als Schleifen Gleicher Syntax für verschiedene Zwecke Neuer Syntax zum erlernen Code leserlicher und kürzer Debug wesentlich schwieriger PLINQ vereinfacht Multithreading

Basiswissen Lambda Expression var keyword Object Initialization x => x.Length > 5 (x, y) => x == y var keyword var myInteger = 1; var myString = „I‘m a string.“; Object Initialization Person adrian = new Person {Vorname = „Adrian“, Nachname = „Weidermann“}; var adrian = new Person {Vorname = „Adrian“, Nachname = „Weidermann“}; Anonymous Types var adrian = new {Vorname = „Adrian“, Nachname = „Weidermann“}; var tier = new {Gattung = „Nashorn“, Name = „Kleiner Muck“, Gewicht = 350, Alter = 2}; Extionsion Methods /// <summary> /// Extends all Enumerables. /// </summary> public static class EnumerableExtension { /// <summary> /// Executes the action for every element in list. /// </summary> /// <typeparam name="T">The Target type.</typeparam> /// <param name="source">The enumerable source.</param> /// <param name="action">The action to do.</param> public static void ForEach<T>(this Ienumerable<T> source, Action<T> action) { foreach (var item in source) { action(item); } } }

Sprachdetails Query Syntax An SQL angelehnt Übersichtlicher bei den meisten komplizierten Abfragen from x in persons where x.Vorname == „Adrian“ Fluent Syntax Platzsparender Übersichtlicher bei den meisten einfachen Abfragen persons.Where(x => x.Vorname == „Adrian“)

Restriction Operators Where from customer in Customers where customer.Fax != null select customer Customers.Where((customer, index) => customer.Fax != null && index < 5)

Projection Operators Select SelectMany from customer in Customers select new {Name = customer.ContactName.ToUpper(), Phone = customer.Phone} Customers.Select((customer, index) => new {Name = customer.ContactName.ToUpper(), Phone = customer.Phone, Index = index}) SelectMany from customer in Customers from order in customer.Orders select new {Name = customer.ContactName.ToUpper(), Phone = customer.Phone, order.OrderDate} Customers.SelectMany((customer, index) => customer.Orders.Select(order => „Customer #“ + (index +1) + „ ordered on „ + order.OrderDate.ToString()))

Partitioning Operators Take (from customer in Customers select customer).Take(5) Customers.Take(5) Skip (from customer in Customers select customer).Skip(5) Customers.Skip(5) TakeWhile (from customer in Customers select customer).TakeWhile(customer => customer.Phone != null) Customers.TakeWhile(customer => customer.Phone != null) SkipWhile (from customer in Customers select customer).SkipWhile(customer => customer.Phone != null) Customers.SkipWhile(customer => customer.Phone != null)

Ordering Operators OrderBy OrderByDescending ThenBy ThenByDescending from customer in Customers orderby customer.ContactName select customer Customers.OrderBy(customer => customer.ContactName) OrderByDescending from customer in Customers orderby customer.ContactName descending select customer Customers.OrderByDescending(customer => customer.ContactName) ThenBy from customer in Customers orderby customer.City descending, customer.ContactName select customer Customers.OrderBy(customer => customer.City).ThenBy(customer => customer.ContactName) ThenByDescending from customer in Customers orderby customer.City descending, customer.ContactName descending select customer Customers.OrderBy(customer => customer.City).ThenByDescending(customer => customer.ContactName) Reverse Customers.Reverse()

GroupBy Grouping Operators from customer in Customers group customer by customer.City into city select city Customers.GroupBy(customer => customer.City)

Set Operators Distinct Union Intersect Except (from customer in Customers select customer).Distinct() Customers.Distinct() Union (from customer in Customers select customer.ContactName).Union(from order in Orders select order.CustomerID) Customers.Select(customer => customer.ContactName).Union(Orders.Select(order => order.CustomerID)) Intersect (from customer in Customers select customer.ContactName).Intersect(from order in Orders select order.CustomerID) Customers.Select(customer => customer.ContactName).Intersect(Orders.Select(order => order.CustomerID)) Except (from customer in Customers select customer.ContactName).Except(from order in Orders select order.CustomerID) Customers.Select(customer => customer.ContactName).Except(Orders.Select(order => order.CustomerID))

Conversion Operators ToArray ToList ToDictionary OfType Cast ToLookup (from customer in Customers select customer).ToArray() Customers.ToArray() ToList (from customer in Customers select customer).ToList() Customers.ToList() ToDictionary (from customer in Customers select customer).ToDictionary(customer => customer.ContactName) Customers.ToDictionary(customer => customer.ContactName) OfType (from customer in Customers select customer.PostalCode).OfType<Int32>() Customers.Select(customer => customer.PostalCode).OfType<Int32>() Cast (from customer in Customers select customer.PostalCode).Cast<Int32>() Customers.Select(customer => customer.PostalCode).Cast<Int32>() ToLookup (from customer in Customers select customer).ToLookup(customer => customer.City = "Vienna") Customers.ToLookup(customer => customer.City = "Vienna") AsEnumerable (from customer in Customers select customer).AsEnumerable().Reverse() Customers.AsEnumerable().Reverse()

Element Operators First FirstOrDefault Single SingleOrDefault (from customer in Customers select customer).First(customer => customer.PostalCode == null) Customers.First(customer => customer.PostalCode == null) FirstOrDefault (from customer in Customers select customer).FirstOrDefault(customer => customer.PostalCode == null) Customers.FirstOrDefault(customer => customer.PostalCode == null) Single (from customer in Customers select customer).Single(customer => customer.PostalCode == null) Customers.Single(customer => customer.PostalCode == null) SingleOrDefault (from customer in Customers select customer).SingleOrDefault(customer => customer.PostalCode == null) Customers.SingleOrDefault(customer => customer.PostalCode == null) ElementAt (from customer in Customers select customer).ElementAt(1) Customers.ElementAt(1) ElementAtOrDefault (from customer in Customers select customer).ElementAtOrDefault(1) Customers.ElementAtOrDefault(1) DefaultIfEmpty (from customer in Customers select customer).DefaultIfEmpty().First() Customers.DefaultIfEmpty().First()

Generation Operators Range Repeat Empty from n in Enumerable.Range(100, 50) select new { Number = n, OddEven = n % 2 == 1 ? "odd" : "even" } Repeat Enumerable.Repeat(„RepeatMe“, 10) Empty Enumerable.Empty<string>()

Quantifiers Any (from customer in Customers select customer).Any(customer => customer.Country != null) Customers.Any(customer => customer.Country != null) All (from customer in Customers select customer).All(customer => customer.Country != null) Customers.All(customer => customer.Country != null)

Aggregate Operators Count LongCount Sum Min Max Average Aggregate from customer in Customers group customer by customer.ContactTitle into customerGrouped select new { Customer = customerGrouped.Key, OrderCount = customerGrouped.Count() } Customers.Count() LongCount from customer in Customers group customer by customer.ContactTitle into customerGrouped select new { Customer = customerGrouped.Key, OrderCount = customerGrouped.LongCount() } Customers.LongCount() Sum (from order in Orders select order).Sum(order => order.Freight) Min (from order in Orders select order).Min(order => order.Freight) Orders.Min(order => order.Freight) Max (from order in Orders select order).Max(order => order.Freight) Orders.Max(order => order.Freight) Average (from order in Orders select order).Average(order => order.Freight) Orders.Average(order => order.Freight) Aggregate (from order in Orders select order).Aggregate(100, (orderIDBalance, nextValue) => ((nextValue.OrderID <= orderIDBalance) ? (orderIDBalance - nextValue.OrderID) : orderIDBalance)) Orders.Select(order => order.OrderID).Aggregate((orderID, nextValue) => orderID * nextValue)

Miscellaneous Operators Concat (from customer in Customers select customer.ContactName).Concat(from order in Orders select order.ShipCity) Customers.Select(customer => customer.ContactName).Concat(Orders.Select(order => order.ShipCity)) EqualAll (from customer in Customers select customer.ContactName).SequenceEqual(from order in Orders select order.ShipCity) Customers.Select(customer => customer.ContactName).SequenceEqual(Orders.Select(order => order.ShipCity)) Let from customer in Customers let AddressInfo = customer.Address + " " + customer.PostalCode + " " + customer.City + " " + customer.Country select new { Name = customer.ContactName, Address = AddressInfo } Customers.Select(customer => new { Customer = customer, AddressInfo = customer.Address + " " + customer.PostalCode + " " + customer.City + " " + customer.Country }).Select(newCustomer => new { Name = newCustomer.Customer.ContactName, Address = newCustomer.AddressInfo })

JoinOperators Join GroupJoin LeftOuterJoin from customer in Customers join order in Orders on customer.CustomerID equals order.CustomerID select new { Name = customer.ContactName, OrderDate = order.OrderDate} Customers.Join(Orders, customer => customer.CustomerID, order => order.CustomerID, (customer, order) => new { Name = customer.ContactName, OrderDate = order.OrderDate}) GroupJoin from customer in Customers join order in Orders on customer.CustomerID equals order.CustomerID into groupedOrder select new { Name = customer.ContactName, OrderDate = groupedOrder} Customers.GroupJoin(Orders, customer => customer.CustomerID, order => order.CustomerID, (customer, groupedOrder) => new { Name = customer.ContactName, OrderDate = groupedOrder}) LeftOuterJoin from customer in Customers join order in Orders on customer.CustomerID equals order.CustomerID into groupedOrder from order in groupedOrder select new { Name = customer.ContactName, OrderDate = groupedOrder}

LINQ to XML Erlaubt Lesen, schreiben von XML Dokumenten Vereinfacht lesen und schreiben von XML Daten

Object Model

Erklärung Object Models XDocument Ein XML Sheet (inkludiert laden und speichern) XDocument.Parse(String) erlaubt erstellen von Xelement aus string XDeclaration Informationen zum Sheet XDocumentType Definiert den Dokumenten Typ <!DOCTYPE Customers SYSTEM „Customerss.dtd"> XText Alle String Objekte XCData Übernimmt den Text 1 : 1 also kein < zB. nötig <![CDATA[<Customer>Adrian</Customer>]]> XElement Child Element/Node im XML <Customer></Customer> XElement.Parse(String) erlaubt erstellen von Xelement aus string

XProcessingInstruction XAttribute Attribut eines Objektes <Customer Name=„Adrian“/> XProcessingInstruction Informationen für Anwendungen <?CustomerOption remove?> XComment Kommentar <!-- The customer --> XNamespace Namespace XStreamingElement Erlaubt einbetten von LINQ

Beispiel SEPA

Beispiel SEPA 2

Query Syntax Nodes Element(s) Anchestor Descendants Attribute Customers.Nodes() Customers.NodesBeforeSelf() Customers.NodesAfterSelf() Element(s) Customers.Elements() Customer.Element(„ContactName“) Customers.ElementsAfterSelf() Customers.ElementsBeforeSelf() Anchestor Orders.Anchestors() Orders.AnchestorsAndSelf() Descendants Customers.Descendants() Customers.DescendantsAndSelf() Attribute XElement.Attribute() XElement.Attributes() Annotation XObject.Annotation() XObject.Annotations()

Data Modification Add Remove ReplaceAll XContainer.Add(XElement) XContainer.AddFirst(XElement) XContainer.AddBeforeSelf(XElement) XContainer.AddAfterSelf(XElement) Remove XNode.Remove() IEnumerable<T>.RemoveAll() ReplaceAll XElement.ReplaceAll(XElement, XElement)

Das wars… vorerst ;)