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 ;)