1 / 104

LINQ Complete Unit 4

Learn about LINQ (Language Integrated Query) and how it simplifies querying data in diverse data sources. Explore the syntax, types, and advantages of LINQ.

Download Presentation

LINQ Complete Unit 4

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. LINQComplete Unit 4 Ashima Wadhwa

  2. LINQ • Developers across the world have always encountered problems in querying data because of the lack of a defined path and need to master a multiple of technologies like SQL, Web Services, XQuery, etc. • Introduced in Visual Studio 2008 and designed by Anders Hejlsberg, LINQ (Language Integrated Query) allows writing queries even without the knowledge of query languages like SQL, XML etc. LINQ queries can be written for diverse data types.

  3. Syntax of LINQ • There are two syntaxes of LINQ. These are the following ones. • Lamda (Method) Syntax Example var longWords = words.Where( w => w.length > 10); int longWords = words.Where(w=> w.length > 10)

  4. Syntax of LINQ • Query (Comprehension) Syntax Example var longwords = from w in words where w.length > 10; int longwords = from w in words where w.length > 10;

  5. Types of LINQ • The types of LINQ are mentioned below in brief. • LINQ to Objects • LINQ to XML(XLINQ) • LINQ to DataSet • LINQ to SQL (DLINQ) • LINQ to Entities • Apart from the above, there is also a LINQ type named PLINQ which is Microsoft’s parallel LINQ.

  6. LINQ Architecture in .NET • LINQ has a 3-layered architecture in which the uppermost layer consists of the language extensions and the bottom layer consists of data sources that are typically objects implementing

  7. Query Expressions • Query expression is nothing but a LINQ query, expressed in a form similar to that of SQL with query operators like Select, Where and OrderBy. Query expressions usually start with the keyword “From”. • To access standard LINQ query operators, the namespace System.Query should be imported by default

  8. Need For LINQ • Prior to LINQ, it was essential to learn C#, SQL, and various APIs that bind together the both to form a complete application. Since, these data sources and programming languages face an impedance mismatch; a need of short coding is felt. • Below is an example of how many diverse techniques were used by the developers while querying a data before the advent of LINQ.

  9. SqlConnectionsqlConnection = new SqlConnection(connectString); SqlConnection.Open(); System.Data.SqlClient.SqlCommandsqlCommand = new SqlCommand(); sqlCommand.Connection = sqlConnection; sqlCommand.CommandText = "Select * from Customer"; return sqlCommand.ExecuteReader(CommandBehavior.CloseConnection) • Interestingly, out of the featured code lines, query gets defined only by the last two. Using LINQ, the same data query can be written in a readable color-coded form like the following one mentioned below that too in a very less time. • Northwind db = new Northwind(@"C:\Data\Northwnd.mdf"); • var query = from c in db.Customers select c;

  10. Advantages of LINQ • LINQ offers syntax highlighting that proves helpful to find out mistakes during design time. • LINQ offers IntelliSense which means writing more accurate queries easily. • Writing codes is quite faster in LINQ and thus development time also gets reduced significantly. • LINQ makes easy debugging due to its integration in the C# language. • Viewing relationship between two tables is easy with LINQ due to its hierarchical feature and this enables composing queries joining multiple tables in less time. • LINQ allows usage of a single LINQ syntax while querying many diverse data sources and this is mainly because of its unitive foundation. • LINQ is extensible that means it is possible to use knowledge of LINQ to querying new data source types. • LINQ offers the facility of joining several data sources in a single query as well as breaking complex problems into a set of short queries easy to debug.

  11. The General Form of a Query • A query must begin with the keyword from and end with either a select or group clause. • The select clause determines what type of value is enumerated by the query. • The group clause returns the data by groups, with each group being able to be enumerated individually. • The where clause specifies criteria that an item must meet in order for it to be returned.

  12. set of contextual keywords used by LINQ query • ascending • by • descending • equals • From • group • in • into • join • let • on • orderby • select • where

  13. Query clause keywords • from • Group • join • let • orderby • select • where

  14. Filter Values with where clause • where is used to filter the data returned by a query, by specifying a condition • We can use where to filter data based on more than one condition. • One way to do this is through the use of multiple where clauses. • Second way is to use logical AND/OR

  15. class IntroToLINQ { static void Main() { // The Three Parts of a LINQ Query: // 1. Data source. int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 }; // 2. Query creation. // numQuery is an IEnumerable<int> varnumQuery = from num in numbers where (num % 2) == 0 select num; // 3. Query execution. foreach (int num in numQuery) { Console.Write("{0,1} ", num); } } }

  16. using System; using System.Linq; class Program { static void Main() { string[] words = {"hello", "wonderful", "LINQ", "beautiful", "world"}; //Get only short words varshortWords = from word in words where word.Length <= 5 select word; //Print each word out foreach (var word in shortWords) { Console.WriteLine(word); } Console.ReadLine(); } }

  17. string[] musicalArtists = { "Adele", "Maroon 5", "Avril Lavigne" }; IEnumerable<string> aArtists = from artist in musicalArtists where artist.StartsWith("A") select artist; foreach (var artist in aArtists) { Console.WriteLine(artist); }

  18. using System; using System.Linq; class Program { static void Main() { int[] array = { 1, 2, 3, 6, 7, 8 }; // Query expression. var elements = from element in array orderby element descending where element > 2 select element; // Enumerate. foreach (var element in elements) { Console.Write(element); Console.Write(' '); } Console.WriteLine(); } }

  19. Output 8 7 6 3

  20. var queryLondonCustomers = from cust in customers where cust.City == "London" select cust; where cust.City=="London" && cust.Name == "Devon” where cust.City == "London" || cust.City == "Paris"

  21. var queryLondonCustomers3 = from cust in customers where cust.City == "London" orderby cust.Name ascending select cust;

  22. Introduction to XMLExtensible Markup Language

  23. What is XML • XML stands for eXtensible Markup Language. • A markup language is used to provide information about a document. • Tags are added to the document to provide the extra information. • XML documents are used to transfer data from one place to another often over the Internet. • XML subsets are designed for particular applications.

  24. Advantages of XML • XML is text (Unicode) based. • Takes up less space. • Can be transmitted efficiently. • One XML document can be displayed differently in different media. • Html, video, CD, DVD, • You only have to change the XML document in order to change all the rest. • XML documents can be modularized. Parts can be reused.

  25. Example of an HTML Document <html> <head><title>Example</title></head. <body> <h1>This is an example of a page.</h1> <h2>Some information goes here.</h2> </body> </html>

  26. Example of an XML Document <?xml version=“1.0”/> <address> <name>Alice Lee</name> <email>alee@aol.com</email> <phone>212-346-1234</phone> <birthday>1985-03-22</birthday> </address>

  27. Difference Between HTML and XML • HTML tags have a fixed meaning and browsers know what it is. • XML tags are different for different applications, and users know what they mean. • HTML tags are used for display. • XML tags are used to describe documents and data.

  28. XML Rules • Tags are enclosed in angle brackets. • Tags come in pairs with start-tags and end-tags. • Tags must be properly nested. • <name><email>…</name></email> is not allowed. • <name><email>…</email><name> is. • Tags that do not have end-tags must be terminated by a ‘/’. • <br /> is an html example.

  29. More XML Rules • Tags are case sensitive. • <address> is not the same as <Address> • Tags may not contain ‘<‘ or ‘&’. • Tags follow Java naming conventions, except that a single colon and other characters are allowed. They must begin with a letter and may not contain white space. • Documents must have a single root tag that begins the document.

  30. Implicitly Typed Local Variables • Local variables can be given an inferred "type" of var instead of an explicit type. The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement. The inferred type may be a built-in type, an anonymous type, a user-defined type, or a type defined in the .NET Framework class library.

  31. Examples var i = 5; var s = "Hello"; var d = 1.0; var numbers = new int[] {1, 2, 3}; The implicitly typed local variable declarations above are precisely equivalent to the following explicitly typed declarations: int i = 5; string s = "Hello"; double d = 1.0; int[] numbers = new int[] {1, 2, 3};

  32. local variable declarator in an implicitly typed local variable declaration is subject to the following restrictions: • The declarator must include an initializer. • The initializer must be an expression. • The initializer expression must have a compile-time type which cannot be the null type. • The local variable declaration cannot include multiple declarators. • The initializer cannot refer to the declared variable itself

  33. Examples var x; // Error, no initializer to infer type from var y = {1, 2, 3}; // Error, collection initializer not permitted Var z = null; // Error, null type not permitted var u = x => x + 1; // Error, lambda expressions do not have a type var v = v++; // Error, initializer cannot refer to variable itself With foreach loop int[] numbers = { 1, 3, 5, 7, 9 }; foreach (var n in numbers) Console.WriteLine(n);

  34. class IntroToLINQ { static void Main() { int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 }; var numQuery = from num in numbers where (num % 2) == 0 select num; foreach (int num in numQuery) { Console.Write("{0,1} ", num); } } }

  35. Anonymous types Anonymous types allow us to create new type without defining them. This is way to defining read only properties into a single object without having to define type explicitly. Here Type is generating by the compiler and it is accessible only for the current block of code. The type of properties is also inferred by the compiler.We can create anonymous types by using “new” keyword together with the object initializer.

  36. Anonymous types • var anonymousData = new                    {                        ForeName = "Jignesh",                        SurName = "Trivedi"                    };Console.WriteLine("First Name : " + anonymousData.ForeName);

  37. Anonymous Types with LINQ Example • Anonymous types are also used with the "Select" clause of LINQ query expression to return subset of properties.

  38. Example class MyData {    public string FirstName { get; set; }    public string LastName { get; set; }    public DateTime DOB { get; set; }    public string MiddleName { get; set; }}

  39. static void Main(string[] args){// Create Dummy Data to fill Collection.    List<MyData> data = new List<MyData>();    data.Add(new MyData { FirstName = "Jignesh", LastName = "Trivedi", MiddleName = "G", DOB = new DateTime(1990, 12, 30) });     data.Add(new MyData { FirstName = "Tejas", LastName = "Trivedi", MiddleName = "G", DOB = new DateTime(1995, 11, 6) }); data.Add(new MyData { FirstName = "Rakesh", LastName = "Trivedi", MiddleName = "G", DOB = new DateTime(1993, 10, 8) });   data.Add(new MyData { FirstName = "Amit", LastName = "Vyas", MiddleName = "P", DOB = new DateTime(1983, 6, 15) }); data.Add(new MyData { FirstName = "Yash", LastName = "Pandiya", MiddleName = "K", DOB = new DateTime(1988, 7, 20) });} 

  40. var anonymousData = from pl in data                        select new { pl.FirstName, pl.LastName }; foreach (var m in anonymousData)    {        Console.WriteLine("Name : " + m.FirstName + " " + m.LastName);    }}

  41. OUTPUT

  42. Rules • Anonymous type is class type which is directly derived from “System.Object” and it cannot be cast any type other than the object. • The Compiler generates a name for each anonymous type. • It cannot be declared fields, events, or the return type of a method which having anonymous type. • Same as it cannot be declared formal parameter of method, property, constructor or indexer which having anonymous type.

  43. Extension Methods • Open Closed Principle(OCP) states that we should design our types in such a way that it should be open for extension but closed for modification. Extension methods in C# can be thought of as a mechanism to implement the OCP for user defined types or even the primitive types and the types defined in the framework. • Extension methods allow us to extend an existing type by adding additional methods and functionality to an existing type without needing to change the code of that type(we might even not have code in most cases). Prior to the existence of extension methods, developers used to create their own types and either inherit or contain the existing type inside these types. These new types were more of the wrappers on the existing types rather than the actual extensions of these types.

  44. struct MyInt { int value; public MyInt(int val) { this.value = val; } public int Negate() { return -value; } } static void Main(string[] args) { // Old way of using wrappers for extensions MyInt i = new MyInt(53); Console.WriteLine(i.Negate()); }

  45. To create an extension method, we need to take the following steps: • Define a static class. • Define a public static function in this class with the name desired as the new method name and return value as per the functionality. • Pass the parameter of type that you want to extend. The important thing here is to put a this keyword before the parameter to tell the compiler that we need to extend this type and we are not really expecting this type as argument.

  46. // Extending using Extension methods static class MyExtensionMethods { public static int Negate(this int value) { return -value; } } static void Main(string[] args) { //Using extension method int i2 = 53; Console.WriteLine(i2.Negate()); }

  47. / Extending using Extension methods static class MyExtensionMethods { public static int Negate(this int value) { return -value; } public static int Multiply(this int value, int multiplier) { return value * multiplier; } } static void Main(string[] args) { // Passing arguments in extension methods int i3 = 10; Console.WriteLine("Passing arguments in extension methods: {0}", i3.Multiply(2)); }

  48. Points that need to be remembered before implementing extension methods. • First of which is that the extension methods can only access the public properties of the type. • The extension method signature should not be same as an existing method of the type. • The extension method for a type can only be used if the namespace that contains the extension method is in scope. • In case we define extension methods in such a way that it overloads an existing method of the original type and the calls are getting ambiguous then the overload resolution rule will always choose the instance method over the extension method. • If there is some ambiguity between two extension methods then the method containing more specific arguments will get called.

  49. LINQ and Extension Methods • The most common extension methods are the LINQ standard query operators that add query functionality to the existing System.Collections.IEnumerable and System.Collections.Generic.IEnumerable<T> types.  • Group by • Average • Order by

More Related