This document provides an overview of LINQ (Language Integrated Query) and its capabilities. It introduces LINQ to Objects, LINQ to SQL, and LINQ to XML. LINQ allows developers to query data structures using SQL-like syntax directly in code and integrates with various .NET languages and data sources.
4. Introduction RDBMS Business Logic Windows UI Web UI Console Web Service Windows Service Impedance Mismatch Data Access
5.
6.
7. Automatic Properties public class Person { // C# 2.0 private string _firstName, _lastName; private int _age; public string FirstName { get { return _firstName; } set { _firstName = value; } } public string LastName { get { return _lastName; } set { _lastName = value; } } public int Age { get { return _age; } set { _age = value; } } } public class Person { // C# 3.0 public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } }
8. Object Initializers // C# 2.0 Person p = new Person(); p.FirstName = "Bart"; p.LastName = "Simpson"; p.Age = 12; // C# 3.0 Person p = new Person() { FirstName = "Bart", LastName = "Simpson", Age = 12 };
9. Collection Initializers // C# 3.0 List<Person> people = new List<Person>(); people.Add(new Person() { FirstName = "Bart", LastName = "Simpson", Age = 12 }); people.Add(new Person() { FirstName = "Clark", LastName = "Kent", Age = 35 }); people.Add(new Person() { FirstName = "Peter", LastName = "Parker", Age = 30 }); // C# 3.0 var people = new List<Person>() { new Person() { FirstName = "Bart", LastName = "Simpson", Age = 12 }, new Person() { FirstName = "Clark", LastName = "Kent", Age = 35 }, new Person() { FirstName = "Peter", LastName = "Parker", Age = 30 } };
10. Anonymous Types var people = new[] { new { FirstName = "Clark", LastName = "Kent", Age = 36 }, new { FirstName = "Peter", LastName = "parker", Age = 26 }, new { FirstName = "Bart", LastName = "Simpson", Age = 11 } }; foreach (var i in people) Console.WriteLine("{0} {1} ({2})", i.FirstName, i.LastName, i.Age); Console.WriteLine(people[0].GetType().FullName); // ??? In which the type name is generated by the compiler and Is not available at the source code level.
11.
12. Extension Methods public static class MyExtensions { public static string UpperLower( this string str, bool upperFirst) { StringBuilder newString = new StringBuilder(str.Length); for (int i = 0; i < str.Length; i++) { newString.Append(upperFirst ? char.ToUpper(str[i]) : char.ToLower(str[i])); upperFirst = !upperFirst; } return newString.ToString(); } } string input = Console.ReadLine(); Console.WriteLine("calling extension method for {0}: {1}", input, input. UpperLower (true));
13. Lambda Expressions A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types. var x => x+1; //Implicitly typed expression. var x => { return x+1;} //Implicitly type statement. int x => x+1; //Explicitly typed expression. int x => {return x+1;} //Explicitly type statement.
14. var prs = Process.GetProcesses() .Where(process => process.WorkingSet64 > 20 * 1024 * 1024) .OrderByDescending(process => process.WorkingSet64) .Select(process => new { process.Id, Name = process.ProcessName }); Extension methods Local variable type inference Anonymous types Object initializers Lambda expressions Language Extensions
15.
16. The LINQ Project C# 3.0 Visual Basic 9.0 Others .NET Language Integrated Query
17. LINQ to Objects C# 3.0 Visual Basic 9.0 Others .NET Language Integrated Query
18.
19.
20. LINQ to SQL C# 3.0 Visual Basic 9.0 Others .NET Language Integrated Query
21. LINQ to SQL Architecture Enumerate SQL Query or SProc Rows Objects SubmitChanges() DML or SProcs Application LINQ to SQL from c in db.Customers where c.City == "London" select c.CompanyName SELECT CompanyName FROM Customer WHERE City = 'London' db.Customers.Add(c1); c2.City = “Seattle"; db.Customers.Remove(c3); INSERT INTO Customer … UPDATE Customer … DELETE FROM Customer …
22.
23. Querying SQL SqlConnection c = new SqlConnection(…); c.Open(); SqlCommand cmd = new SqlCommand( @"SELECT c.Name, c.Phone FROM Customers c WHERE c.City = @p0"); cmd.Parameters["@p0"] = "London"; DataReader dr = c.Execute(cmd); while (dr.Read()) { string name = r.GetString(0); string phone = r.GetString(1); DateTime date = r.GetDateTime(2); } r.Close(); Accessing relational data today Queries in quotes Loosely bound arguments Loosely typed result sets No compile time checks
24. LINQ to SQL public class Customer { … } public class Northwind: DataContext { public Table<Customer> Customers; … } Northwind db = new Northwind(…); var contacts = from c in db.Customers where c.City == "London" select new { c.Name, c.Phone }; Accessing relational data with LINQ Classes describe data Strongly typed connection Integrated query syntax Strongly typed results Tables are like collections
25. Language Extensions var contacts = from c in dc.GetTable<customers>() where c.State == "WA" select new { c.Name, c.Phone }; var contacts = customers .Where(c => c.State == "WA") .Select(c => new { c.Name, c.Phone }); Extension methods Lambda expressions Query expressions Object initializers Anonymous types Local variable type inference
26. LINQ to XML C# 3.0 Visual Basic 9.0 Others .NET Language Integrated Query
27.
28. LINQ to XML XmlDocument doc = new XmlDocument(); XmlElement contacts = doc.CreateElement("contacts"); foreach (Customer c in customers) if (c.Country == "USA") { XmlElement e = doc.CreateElement("contact"); XmlElement name = doc.CreateElement("name"); name.InnerText = c.CompanyName; e.AppendChild(name); XmlElement phone = doc.CreateElement("phone"); phone.InnerText = c.Phone; e.AppendChild(phone); contacts.AppendChild(e); } doc.AppendChild(contacts); Programming XML today <contacts> <contact> <name>Great Lakes Food</name> <phone>(503) 555-7123</phone> </contact> … </contacts> Imperative model Document centric No integrated queries Memory intensive
29. LINQ to XML XElement contacts = new XElement("contacts", from c in customers where c.Country == "USA" select new XElement("contact", new XElement("name", c.CompanyName), new XElement("phone", c.Phone) ) ); Programming XML with LINQ Declarative model Element centric Integrated queries Smaller and faster
From time immemorial (i.e. from 1990 th ) people use Relational DBMS for data storing and Object Oriented language for data behavior implementation. RDBMS stores and processes quickly large amounts of data by. And Object Oriented code manages them by clear and well-supportable way. In enterprise applications the Business Functionality Tier is a central component. As a rule it contains a set of entry points, that are exploited by other components. These components use the business functionality tier in various ways. Some performs a OrderItem of short operations, initiated interactively. Response time of these operations must be appropriate. Others performs large work like data import or transferring data to other applications. Independently on their type, the components use the same functionality, coded inside business functionality tier. The problem is that the functionality that is intended for interactive components, works slowly for B2B components. This effect is caused by well-known problem between object oriented and relational point of view. The problem and has name Impedance Mismatch. Data are represented variously in object code and in relational data store. Business functionality level sees data in form of object tree, while relational data storage represents them in form of tables. This difference mitigated by special Data Access Level, that contains automatically generated objects for all business entities represented in the database and provides framework that can load and synchronize them with database. There are a couple ORM tools that support this functionality. But as soon as relational records are wrapped into objects, performance of thee application slow down. Because business functionality level sends them to database record by record, separately. At the same time we know that relational DBMS can process large amounts of data really quickly if only they are presented in form of relational tables, The problem become critical firstly in B2B part of the enterprise application. Standard solution that is commonly used is replacing of object-oriented pieces of code with pieces of clear SQL code. Or creation of stored procedures and calling them directly passing the business functionality level. The performance problem goes away, but other problem appears. Application starts to contain twice coded functionality. Both branches must work equally. So when the functionality is changed, developers are obliged not to forget to change it in both branches and then test the sameness of the branches. Two different approaches This causes significant overhead in development and support processes.