Beginning LINQ by Itorian.com

Embed Size (px)

Citation preview

  • 7/28/2019 Beginning LINQ by Itorian.com

    1/36

    Beginning LINQA new fashion to write Queries and address the impedance

    mismatch between programming languages and database.

    Abhimanyu Kumar VatsaMicrosoft MVP, ASP.NET/IISBlog:www.itorian.comTwitter:http://twitter.com/itorianFacebook:https://www.facebook.com/2050.itorian

    http://www.itorian.com/http://www.itorian.com/http://www.itorian.com/http://twitter.com/itorianhttp://twitter.com/itorianhttp://twitter.com/itorianhttps://www.facebook.com/2050.itorianhttps://www.facebook.com/2050.itorianhttps://www.facebook.com/2050.itorianhttps://www.facebook.com/2050.itorianhttp://twitter.com/itorianhttp://www.itorian.com/
  • 7/28/2019 Beginning LINQ by Itorian.com

    2/36

    This e-book is based on my series of LINQ posts and Im just consolidang all blog posts here.

  • 7/28/2019 Beginning LINQ by Itorian.com

    3/36

    ContentsPart 1

    In this part you will learn what is LINQ, its benefits and comparison with previous

    approach?

    Part 2

    In this part you will learn various approaches used in LINQ like LINQ to Array, XML and

    SQL.

    Part 3

    In this part you will learn something on Genericlike what are generic types, why we need it

    in LINQ?

    Part 4

    In this part you will learn how to setup a demo project to explore LINQ queries.

    Part 5

    In this part you will learn how to select records using LINQ Query and will explore its

    internals.

    Part 6

    In this part you will learn something like filtering, ordering, grouping and joining using

    LINQ.

    Part 7

    In this part you will learn how to use concatekey in LINQ query to do joins on multiple

    tables.

    Part 8

    In this part you will learn how to customize the LINQ s selectstatement in various ways.

    Part 9

    In this part you will learn how to transform data source objects into XML.

    Part 10

    In this part you will learn how to perform some calculations inside LINQ Query.

    Part 11

    In this part you will look at some differences between LINQ Query Syntax and Method

    Syntax used in LINQ.

  • 7/28/2019 Beginning LINQ by Itorian.com

    4/36

  • 7/28/2019 Beginning LINQ by Itorian.com

    5/36

    // Update record using another Command object::::::::::::::::::::c.Close(); //Close conneconThis is not only huge code, but theres also no way for the C# compiler to check our query against our

    use of the data it returns. When e retrieve the employees name we have to know the columns

    posion in the database table to nd it in the result. Its a common mistake to retrieve the wrong

    column and get a type excepon or bad data at run me. But, with LINQ you just need to perform three disnct acons:

    1. Obtain the data source.2. Create the query.3. Execute the query.

    And you all done.

  • 7/28/2019 Beginning LINQ by Itorian.com

    6/36

    As I said in Part 1, with LINQ you just need to perform three disnct acons: Obtain the Data Source,

    Create the query and Execute the query, you will noce it in sample programs given below. We will

    create Console Apps and test various LINQ concepts. I will walk through very simple programs here

    and in coming part will dig in depth.LINQ has a great power of querying on any source of data that could be the collecons of objects (in

    memory data, like array), SQL Database or XML les. We can easily retrieve data from any object that

    implements the IEnumerable interface.

    LINQ to ArrayLets look at a Program to nd Even Number using LINQ to Array.

    If you execute above program, you will get 2 4 6 8 10 as output. You will noce 3 acons above,

    these acons will be changed always depending upon our project requirement. In above example,

    data source was an array that implicitly supports the generic IEnumerable interface.

    Part 2In this part you will learn various approaches used in LINQ like LINQ to Array, XML and SQL.

    http://1.bp.blogspot.com/-_uEECebTHuw/UD9TwLxF92I/AAAAAAAAB90/3INz40dCf5U/s1600/1.png
  • 7/28/2019 Beginning LINQ by Itorian.com

    7/36

    LINQ to XMLNow, lets move on to take a look at LINQ to XML example and nd student names from XML le.

    LINQ to XML loads an XML document into a query-able XElement type and then

    IEnumerable loads the query result and using foreach loop we access it. Student.xml

    Program.cs

    http://4.bp.blogspot.com/-lhxGkjRmXac/UD9TxWG_uEI/AAAAAAAAB98/NSg-HQSf5KI/s1600/2.pnghttp://2.bp.blogspot.com/-j17IARO3-uM/UD9TzbDzb6I/AAAAAAAAB-M/0yMPqKnmrVM/s1600/4.png
  • 7/28/2019 Beginning LINQ by Itorian.com

    8/36

    Output

    LINQ to SQLIn LINQ to SQL, rstly we create an object-relaonal mapping at design me either manually or by

    using the Object Relaonal Designer. Then, we write queries against the objects, and at run-me

    LINQ to SQL handles the communicaon with the database.Now, lets look at the sample program:

    http://3.bp.blogspot.com/-w0OFh1tx3zo/UD9T0UBil6I/AAAAAAAAB-U/XZByapn1UVw/s1600/5.pnghttp://3.bp.blogspot.com/-lsYUwZNeEpQ/UD9TyVHjTAI/AAAAAAAAB-E/lPRd0FQcQTc/s1600/3.png
  • 7/28/2019 Beginning LINQ by Itorian.com

    9/36

    Output

    Very simple examples on LINQ so far, nd more in next part.

    http://3.bp.blogspot.com/-xVgUL3uke2Y/UD9T1TIJSSI/AAAAAAAAB-Y/yG-jBew1AOQ/s1600/6.png
  • 7/28/2019 Beginning LINQ by Itorian.com

    10/36

    First of all lets understand what are Arrays, .NET Collecons and .NET Generic Collecons. You will

    see following advantages and disadvantages in examples given below.Collecon Types Advantages DisadvantagesArrays Strongly Typed (Type Safe) Zero Index Based

    Cannot grow the sizeonce inialized

    .NET Collecons (like ArrayList,

    Hashtable etc) Can grow in size Convenient to workwith Add, Remove

    Not Strongly Typed

    .NET Generic Collecons (like

    List, GenericList etc) Type Safe like arrays Can growautomacally like

    ArrayList Convenient to work

    with Add, RemoveNow, lets talk on each of the collecon type given in above table to feel real pain of developments. Array

    Part 3In this part you will learn something on Generic like what are generic types, why we need it in LINQ?

    http://1.bp.blogspot.com/-e-kR7TqXD-4/UECA81ctd1I/AAAAAAAAB_0/1g-SKrpJnpI/s1600/array.png
  • 7/28/2019 Beginning LINQ by Itorian.com

    11/36

    If you use array:1. You cant enter more values beyond the inialized size otherwise you will see a runme error

    saying index was outside the bounds of the array.2. If you declare array as an int type then, you are limited to enter integer values only otherwise

    you will see a compile me error saying cannot implicitly convert type string to int, all

    because array is type safe.3. Array is index based, so you always need to write index number to insert value in collecon.4. You dont have to add or remove methods here.

    ArrayList (System.Collecon

    If you use ArrayList: You will get auto grow feature, means inial size will not limit you. You dont opon to declare the data type at declaraon me on the top, so you can add any

    value like string, Boolean, int etc. Remember to care it in foreach loop at runme. You will have some very useful methods like Remove, RemoveAt, RemoveRange etc. You

    dont have any opon like index.

    http://1.bp.blogspot.com/-aEt67P17gXY/UECA9pDkUvI/AAAAAAAACAA/ivx52FVsYBo/s1600/arraylist.png
  • 7/28/2019 Beginning LINQ by Itorian.com

    12/36

    List (System.Collecon.Generic

    Now, in short we can say, list has both features that we have in array or arraylist.Why we need List (which is generic type) in LINQ?LINQ queries are based on generic types, which were introduced in version 2.0 of the .NET

    Framework. LINQ queries returns collecon and we dont even know what type of data we will get

    from database and that is the reason we use generic type like List, IEnumerable,

    IQueryable etc. For example:

    http://2.bp.blogspot.com/-10qCSfPT0Ko/UECA72gs-qI/AAAAAAAAB_w/quNfbdJfIXg/s1600/2.pnghttp://4.bp.blogspot.com/-2aT4PVpTYrU/UECA-RT2k0I/AAAAAAAACAI/rsDDaoEIOcA/s1600/listgeneric.png
  • 7/28/2019 Beginning LINQ by Itorian.com

    13/36

    In above example, we have used IEnumerable interface and LINQ query and then by using

    foreach loop Im able to get my data.One more example:IEnumerable customerQuery =

    fromcustincustomerswherecust.City =="Bokaro"selectcust;

    foreach(Customer customerincustomerQuery){

    Console.WriteLine(customer.LastName +" = "+ customer.Age);}In above example you can see, using LINQ query Im not only limited to select the string value that isLastName, Im also able to select integer value that is Age.So, this could be the great example of generic classes.Here is some counterpart of Generic Collecons over non-generic collecons:

    Collecons(System.Collecon) Generic Collecon(System.Collecon.Generic)ArrayList ListHashtable DiconaryStack StackQueue Queue

    Now, go ahead and learn rest in next part.

  • 7/28/2019 Beginning LINQ by Itorian.com

    14/36

    First of all, Ill recommend you to watch this video post on YouTube. hp://www.youtube.com/watch?v=yQB4HGmuwY8&feature=player_embeddedI will use my preinstalled Northwind database that you can download fromhereand install it in SQLServer Management Studio.Now, follow the steps to setup a demo project to explore LINQ queries. Before creang new project,

    setup a Northwind database in SQL Server Management Studio.

    Step 1: Creang New ProjectOpen the Visual Studio instance and create a new project New > Project > Console Applicaon and

    name the project whatever you wish.

    Part 4In this part you will learn how to setup a demo project to explore LINQ queries.

    http://www.youtube.com/watch?v=yQB4HGmuwY8&feature=player_embeddedhttp://www.youtube.com/watch?v=yQB4HGmuwY8&feature=player_embeddedhttp://www.microsoft.com/en-in/download/details.aspx?id=23654http://www.microsoft.com/en-in/download/details.aspx?id=23654http://www.microsoft.com/en-in/download/details.aspx?id=23654http://3.bp.blogspot.com/-_7I4IvSVYx4/UEC1M2-K5kI/AAAAAAAACBc/LIVb-MMm2Xg/s1600/1.pnghttp://www.microsoft.com/en-in/download/details.aspx?id=23654http://www.youtube.com/watch?v=yQB4HGmuwY8&feature=player_embedded
  • 7/28/2019 Beginning LINQ by Itorian.com

    15/36

    Step 2: Adding LINQ to SQL ClassesNow, in the soluon explorer add a new item LINQ to SQL Classes by a nice name

    DataNorthwind.dbml.

    This will add all required library as well as classes in your project for database communicaon.

    Actually, this dbml le will become a layer between DB and your project and provide you all the

    IntelliSense features.

    http://3.bp.blogspot.com/-TNVNy3DqxbQ/UEC1OgoN9zI/AAAAAAAACBs/ABJxrw7v6l0/s1600/3.pnghttp://1.bp.blogspot.com/-U8DBeX5OA4Q/UEC1N6N4FMI/AAAAAAAACBk/_etRPlCj9nA/s1600/2.png
  • 7/28/2019 Beginning LINQ by Itorian.com

    16/36

    Step 3: Adding New ConneconOpen Server Explorer and add a new SQL Server connecon, follow the image.

    Once you done with above, now drag the tables from Server Explorer to DataNorthwind.dbml le

    designer.

    http://4.bp.blogspot.com/-FCZ60INamNU/UEC1Pn2ZAzI/AAAAAAAACB0/eECqnQoqQEg/s1600/4.png
  • 7/28/2019 Beginning LINQ by Itorian.com

    17/36

    Now, you will get following DB diagram on designer.

    http://3.bp.blogspot.com/-8YUtZO-WKs8/UEC1RFA4beI/AAAAAAAACCE/TFcvieEdoiI/s1600/6.pnghttp://2.bp.blogspot.com/-1WyQDPHPVEw/UEC1Qc0rAyI/AAAAAAAACB8/8eUOr5oHWGw/s1600/5.png
  • 7/28/2019 Beginning LINQ by Itorian.com

    18/36

    You will noce following things here:1. Got a new connecon string in App.cong le.2. Got every setup required to communicate with DB like DataNorthwindDataContext,

    TableAribute, EntySet etc in DataNorthwind.designer.cs le.Step 4: Coding and Running ProjectNow, setup the project code as given blow and run it.

    We have already seen this code in one of the previous post. Now, we have a demo project setup

    completely and ready to try all the LINQ queries.In upcoming part, we will look at various LINQ queries and will test it in above project.

    http://2.bp.blogspot.com/-cq1US6eia5I/UEC1SHl9FLI/AAAAAAAACCM/XNGL316zC4o/s1600/7.png
  • 7/28/2019 Beginning LINQ by Itorian.com

    19/36

    Selecng RecordsSelecng data using LINQ queries is very simple, you will get full intellisense support while querying

    database and even compile me error check that adds great advantage to LINQ, once you learn it,

    you will love to use this in your every DB projects. I love this, its great.In the image given below, you will nd the sample code for selecng employees FirstName and

    LastName from Employee table of Northwind Database:

    In above image, you can see, Im using same queries two mes, but there is dierence, dont go on

    output screen only. If you look on the code carefully, you will nd Im using IEnumerable

    in the rst block of code and just a var in second block of code. Also note, for

    IEnumerable Im using Employee in foreach loop and for var Im using var in foreach

    loop, you should care it always.Now, what is the dierence between IEnumerable and var?IEnumerableWhen you see a query variable that is typed as IEnumerable, it just means that the query, when it

    is executed, will produce a sequence of zero or more T objects, as given in image blow (just hover the

    mouse on empQuery1 when compiler is on break). When you expand the index[], you will nd

    enre data associated with that row/record.

    Part 5In this part you will learn how to select records using LINQ Query and will explore its internals.

    http://1.bp.blogspot.com/-7fRr6NdwJN4/UEIYEIkGb1I/AAAAAAAACDg/vs5v7cpVYmc/s1600/1.png
  • 7/28/2019 Beginning LINQ by Itorian.com

    20/36

    varIf you prefer, you can avoid generic syntax like IEnumerable by using the var keyword. The var

    keyword instructs the compiler to infer the type of a query variable by looking at the data source

    specied in from clause, no big dierence you sll get all benets.Now, lets talk on the query part.=fromempinNDC.Employees

    selectemp;In C# as in most programming languages a variable must be declared before it can be used. In a LINQ

    query, the from clause comes rst in order to introduce the data source (NDC.Employees) and the

    range variable (emp). NDC is just an instance of the Northwind Data Context that we have created

    in Part 4 and inside this Data Context, we got Employees table and that is why I have used

    NDC.Employees.

    http://1.bp.blogspot.com/-bwApbgtecL8/UEIYGBFiXSI/AAAAAAAACDo/CaOY6bOhgLw/s1600/2.png
  • 7/28/2019 Beginning LINQ by Itorian.com

    21/36

    Execung Query (using foreach loopOnce you done with query your next step will be execung it. Lets go ahead and understand it too.

    As we have bunch of rows/columns in empQuery1 or empQuery2 returned by the LINQ select

    statement, we need to specify which column we want to see in output and thats why, we have used

    e.FirstName and e.LastName, where e is instance of empQuery1 or empQuery2.Alternavely, you can bind empQuery1 or empQuery2 directly to any Data Control like GridView.In upcoming part, you will learn how to lter, order, group, and join using LINQ.

    http://4.bp.blogspot.com/-VWxC2YgrhPM/UEIYG-wtXxI/AAAAAAAACDw/KKFohm5zLqA/s1600/3.png
  • 7/28/2019 Beginning LINQ by Itorian.com

    22/36

    FilterFilter is the most common query operaon to apply a lter in the form of a Boolean expression. The

    lter causes the query to return only those elements for which the expression is true. The result is

    produced by using the where clause. The lter in eect species which elements to exclude from the

    source sequence. Lets look at sample query:DataNorthwindDataContextNDC =newDataNorthwindDataContext();varcustQuery =fromcustinNDC.Customers

    wherecust.Country =="France"selectcust;

    foreach(vareincustQuery){

    Console.WriteLine("Country: "+ e.Country +" || Address: "+ e.Address +" || Phone: "+ e.Phone);}Console.ReadKey();In above query, Im asking for only those records whos Country is France. And in the foreach loop,

    Country, Address and Phone separated by || and the same in output.

    In the same way, if you want to select records where Country is Framce and ContactName starts

    with A, then usevarcustQuery =fromcustinNDC.Customers

    wherecust.Country =="France"&& cust.ContactName.StartsWith("a")selectcust;

    Part 6In this part you will learn something like filtering, ordering, grouping and joining using LINQ.

    http://4.bp.blogspot.com/-vg1wYlW0tYs/UERx_AZFeDI/AAAAAAAACFI/JtlMZHAtmBk/s1600/1.png
  • 7/28/2019 Beginning LINQ by Itorian.com

    23/36

    And, if you want to select records where Country is Framce or ContactName starts with A, then

    usevarcustQuery =fromcustinNDC.Customers

    wherecust.Country =="France"|| cust.ContactName.StartsWith("a")selectcust;

    So, in both query, && is being used for And and || is being used for Or. Now, StartsWith is a LINQ level key that is equivalent to LIKE operator in SQL. You can see it in

    generated query here.

    We will look more only such available keys in coming post.

    OrderThe orderby clause will cause the elements in the returned sequence to be sorted according to the

    default comparer for the type being sorted. For example the following query can be extended to sort

    the results based on the ContactName property. Because ContactName is a string, the default

    comparer performs an alphabecal sort from A to Z.varcustQuery =fromcustinNDC.Customers

    orderbycust.ContactNamedescending//orderby cust.ContactName ascendingselectcust;

    GroupThe group clause enables you to group your results based on a key that you specify. For example you

    could specify that the results should be grouped by the City.varcustQuery =fromcustinNDC.Customers

    wherecust.ContactName.StartsWith("a") groupcustbycust.City;

    When you end a query with a group clause, your results take the form of a list of lists. Each element

    in the list is an object that has a key member and a list of elements that are grouped under that key.

    When you iterate over a query that produces a sequence of groups, you must use a nested foreach

    loop. The outer loop iterates over each group, and the inner loop iterates over each group's

    members.

    http://1.bp.blogspot.com/-97rPiGc6eFg/UERx_6HbvLI/AAAAAAAACFQ/5xMUUUxfLGs/s1600/2.png
  • 7/28/2019 Beginning LINQ by Itorian.com

    24/36

    foreach(vareincustQuery){

    intx = e.Key.Length;Console.WriteLine('\n');Console.WriteLine(e.Key);Console.WriteLine(Repeat('-', x));foreach(Customercine){

    Console.WriteLine("Contact Name : "+ c.ContactName);}

    }And the output will be organized as

    If you must refer to the results of a group operaon, you can use the into keyword to create an

    idener that can be queried further. The following query returns only those groups that contain

    more than two customers:

    http://1.bp.blogspot.com/-nPZ3CBq0KBQ/UERyBQZqF9I/AAAAAAAACFY/dKo-6UfytFw/s1600/3.png
  • 7/28/2019 Beginning LINQ by Itorian.com

    25/36

    varcustQuery =fromcustinNDC.Customersgroupcustbycust.CityintocustGroupwherecustGroup.Count() > 2selectcustGroup;

    And the foreach loop will be same.foreach(vareincustQuery){

    intx = e.Key.Length;Console.WriteLine('\n');Console.WriteLine(e.Key);Console.WriteLine(Repeat('-', x));foreach(Customercine){

    Console.WriteLine("Contact Name : "+ c.ContactName);}

    }You will get following output:

    http://2.bp.blogspot.com/--7cFKOCrkr8/UERyCi0epBI/AAAAAAAACFg/SWE7UOV-YRU/s1600/4.png
  • 7/28/2019 Beginning LINQ by Itorian.com

    26/36

    JoinJoin operaons create associaons between sequences that are not explicitly modeled in the data

    sources. For example you can perform a join to nd all the customers and distributors who have the

    same locaon. In LINQ the join clause always works against object collecons instead of database

    tables directly.Queson: What query we should write to select names from two dierent tables Customer and

    Employee depending upon matching city.Answer: Query will be:varcustQuery =fromcustinNDC.Customers

    joinempinNDC.Employeesoncust.Cityequalsemp.Cityselectnew{ CityName = cust.City, CustomerName = cust.ContactName, EmployeeName =

    emp.FirstName };And in foreach loop, will writeforeach(vareincustQuery){

    Console.WriteLine(e.CityName +" : "+ e.CustomerName +", "+ e.EmployeeName);}Output:

    We can use Group by here to group the output.

    http://1.bp.blogspot.com/-IiF48x5M2Gc/UERyD7MnlWI/AAAAAAAACFk/Hv9qrCMP_M4/s1600/5.png
  • 7/28/2019 Beginning LINQ by Itorian.com

    27/36

    Assume if we have following data source informaon:Student.cs

    classStudent{

    publicintID {get;set; }publicstringName {get;set; }publicstringAddress {get;set; }publicList Marks {get;set; }

    }Teacher.cs

    classTeacher{

    publicintID {get;set; }publicstringName {get;set; }publicstringAddress {get;set; }

    }

    Program.cs//DataSource1List students =newList(){

    newStudent{ ID=1, Name="Abhimanyu K Vatsa", Address="Bokaro", Marks=newList {97, 92, 81, 90}},newStudent{ ID=2, Name="Deepak Kumar", Address="Dhanbad", Marks=newList {70, 56, 87, 69}}, newStudent{ ID=3, Name="Mohit Kumar", Address="Dhanbad", Marks=newList {78, 76, 81, 56}},newStudent{ ID=4, Name="Geeta K", Address="Bokaro", Marks=newList {95, 81, 54, 67}}

    };//DataSource2List teachers =newList(){

    newTeacher{ID=1, Name="Ranjeet Kumar", Address ="Bokaro"},newTeacher{ID=2, Name="Gopal Chandra", Address ="Dhanbad"}

    };And I want to select those Students and Teachers name who are from Bokaro by concat. So, we

    can use LINQ query to create an output sequence that contains elements from more than one input

    sequence. Here it is:

    Part 7In this part you will learn how to use concate key in LINQ query to do joins on multiple tables.

  • 7/28/2019 Beginning LINQ by Itorian.com

    28/36

    //Query using Concatvarquery = (fromstudentinstudents

    wherestudent.Address =="Bokaro"selectstudent.Name)

    .Concat(fromteacherinteacherswhereteacher.Address =="Bokaro"selectteacher.Name);

    And output is:Abhimanyu K VatsaGeeta KRanjeet KumarRemember, this can be done using join also that we have already seen in one of the previous post.

  • 7/28/2019 Beginning LINQ by Itorian.com

    29/36

    Assume following as our data source:Student.cs

    classStudent{

    publicintID {get;set; }publicstringName {get;set; }publicstringAddress {get;set; }publicList Marks {get;set; }

    }Program.csList students =newList(){

    newStudent{ ID=1, Name="Abhimanyu K Vatsa", Address="Bokaro", Marks=newList {97, 92, 81, 90}},newStudent{ ID=2, Name="Deepak Kumar", Address="Dhanbad", Marks=newList {70, 56, 87, 69}}, newStudent{ ID=3, Name="Mohit Kumar", Address="Dhanbad", Marks=newList {78, 76, 81, 56}},newStudent{ ID=4, Name="Geeta K", Address="Bokaro", Marks=newList {95, 81, 54, 67}}

    };Study 1Now, if you want to select only name of students then use following LINQ query:varquery =fromstudentinstudents

    selectstudent.Name;foreach(vareinquery){

    Console.WriteLine(e);}Output:Abhimanyu K VatsaDeepak KumarMohit KumarGeeta K

    Part 8In this part you will learn how to customize the LINQs select statement in various ways.

  • 7/28/2019 Beginning LINQ by Itorian.com

    30/36

    Study 2Now, if you want to select name and address of the student then use following LINQ query:varquery =fromstudentinstudents

    selectnew{ Name = student.Name, Address = student.Address};foreach(vareinquery){

    Console.WriteLine(e.Name +" from "+ e.Address);}Output:Abhimanyu K Vatsa from BokaroDeepak Kumar from DhanbadMohit Kumar from DhanbadGeeta K from BokaroStudy 3Now, if you want to select name, marks and even want to add it then use following query: varquery =fromstudentinstudents

    selectnew{ Name = student.Name, Mark = student.Marks};intsum = 0;foreach(vareinquery){

    Console.Write(e.Name +" : ");foreach(varmine.Mark){

    sum = sum + m;Console.Write(m +" ");

    }Console.Write(": Total- "+ sum);Console.WriteLine();

    }Output:Abhimanyu K Vatsa : 97 92 81 90 : Total- 360Deepak Kumar : 70 56 87 69 : Total- 642Mohit Kumar : 78 76 81 56 : Total- 933Geeta K : 95 81 54 67 : Total- 1230

  • 7/28/2019 Beginning LINQ by Itorian.com

    31/36

    In above query, we have Mark eld that will produce a list and thats why we need to use nested

    foreach loop to get the list item and at the same me we are adding mark items.

  • 7/28/2019 Beginning LINQ by Itorian.com

    32/36

    In-Memory Data-SourceLets have some in-memory data:List students =newList(){

    newStudent{ ID=1, Name="Abhimanyu K Vatsa", Address="Bokaro", Marks=newList {97, 92, 81, 90}},newStudent{ ID=2, Name="Deepak Kumar", Address="Dhanbad", Marks=newList {70, 56, 87, 69}}, newStudent{ ID=3, Name="Mohit Kumar", Address="Dhanbad", Marks=newList {78, 76, 81, 56}},newStudent{ ID=4, Name="Geeta K", Address="Bokaro", Marks=newList {95, 81, 54, 67}}

    };Once we have in-memory data, we can create query on it to generate xml tags and its data as given

    below:varstudentsToXML =newXElement("School", fromstudentinstudentsletx =String.Format("{0},{1},{2},{3}", student.Marks[0], student.Marks[1], student.Marks[2], student.Marks[3])selectnewXElement("Student",

    newXElement("ID", student.ID),newXElement("Name", student.Name),newXElement("Address", student.Address),newXElement("Marks", x)

    )//end of "student");//end of "Root"

    Remember to use System.Xml.Linq namespace that supports XElement in LINQ. Now, its me to

    execute the above query as:stringXMLFileInformaon ="\n"+ studentsToXML;Console.WriteLine(XMLFileInformaon);

    Part 9In this part you will learn how to transform data source objects into XML.

  • 7/28/2019 Beginning LINQ by Itorian.com

    33/36

    Output on Console: Here is what my above code generated for me.

    1Abhimanyu K VatsaBokaro97,92,81,90

    2Deepak KumarDhanbad70,56,87,69

    3Mohit KumarDhanbad78,76,81,56

    4Geeta KBokaro

    95,81,54,67

    If you want to build an real xml le then use following line File.AppendAllText("C:\\Database.xml", XMLFileInformaon);Remember to use System.IO namespace to create xml le on disk. Now, open 'C drive' and le a

    new xml le named Database.xml.Same way you can do this for outer data sources (not in-memory) too.

  • 7/28/2019 Beginning LINQ by Itorian.com

    34/36

    Lets assume we have following data in data source:

    And we want to nd-out Products Total Price by mulplying UnitPrice and UnitInStock data. So, what

    would be the LINQ query to nd the calculated data?

    Lets write a query to solve this:varquery =fromstdinDNDC.Products

    wherestd.SupplierID == 1select new { ProductName = std.ProductName, ProductTotalPrice = String.Format("Total Price =

    {0}",(std.UnitPrice) * (std.UnitsInStock)) };To understand it, look at the above underlined query, you will nd mulplicaon is being done on

    two dierent columns that is on UnitPrice and UnitInStock. Once we get the mulplied value that will

    be casted as string equivalent data and then will assign this to ProductTotalPrice variable. So, wehave ProductName and ProductTotalPrice in query that will be executed in foreach loop to get enre

    data as given below:foreach(varqinquery){

    Console.WriteLine("Product Name: "+ q.ProductName +", Total Price: "+ q.ProductTotalPrice +"");}When you execute above loop, you will get following output:Product Name: Chai, Total Price: Total Price = 702.000000Product Name: Chang, Total Price: Total Price = 323.000000Product Name: Aniseed Syrup, Total Price: Total Price = 130.000000 So, using this you can nd calculated informaon from LINQ query too.

    Part 10In this part you will learn how to perform some calculations inside LINQ Query.

    http://2.bp.blogspot.com/-ofD59XTQRb0/UEcg9265QRI/AAAAAAAACIA/ChEhumFe6Tk/s1600/1.png
  • 7/28/2019 Beginning LINQ by Itorian.com

    35/36

    All the queries we learned in this series so far are known as LINQ Query Syntax that was introduced

    with C# 3.0 release. Actually, at compile me queries are translated into something that the CLR

    understands. So, it makes a method call at runme to produce standard SQL queries that uses real

    SQL keys like WHERE, SELECT, GROUPBY, JOIN, MAX, AVERAGE, ORDERBY and so on. So, we have a

    direct way, to avoid such method calls to produce standard SQL and that is known as Method

    Syntaxes.If you ask me, Ill recommend query syntax because it is usually simpler and more readable; however

    there is no semanc dierence between method syntax and query syntax. In addion, some queries,

    such as those that retrieve the number of elements that match a specied condion, or that retrievethe element that has the maximum value in a source sequence, can only be expressed as method

    calls. The reference documentaon for the standard query operators in the System.Linq namespace

    generally uses method syntax. Therefore, even when geng started wring LINQ queries, it is useful

    to be familiar with how to use method syntax in queries and in query expressions themselves.

    [Source: MSDN]Lets look at the example, which will produce same result using Query Syntax and Method Syntax.int[] numbers =newint[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};varquery1 =fromnuminnumbers

    where(num % 2) == 0selectnum;

    varquery2 = numbers.Where(num => num % 2 == 0).OrderBy(n => n);Console.WriteLine("Query Syntax");foreach(intiinquery1){

    Console.Write(i +"");

    }Console.WriteLine("\nMethod Syntax");foreach(intiinquery2){

    Console.Write(i +" ");}

    Part 11In this part you will look at some differences between LINQ Query Syntax and Method Syntax used in LINQ.

  • 7/28/2019 Beginning LINQ by Itorian.com

    36/36

    If you run above code, you will get following output:Query Syntax2 4 6 8 10Method Syntax2 4 6 8 10In query2, Ill be using Method Syntax and you can see it also produce same output. You can also see

    Im using where, orderby clauses like a method and in the method Im using Lambda syntaxes.I hope you will nd this ebook useful. Thanks for reading.

    Abhimanyu Kumar VatsaMicroso MVP, ASP.NET/IISBlog:www.itorian.comTwitter:http://twitter.com/itorianFacebook:https://www.facebook.com/2050.itorian

    http://www.itorian.com/http://www.itorian.com/http://www.itorian.com/http://twitter.com/itorianhttp://twitter.com/itorianhttp://twitter.com/itorianhttps://www.facebook.com/2050.itorianhttps://www.facebook.com/2050.itorianhttps://www.facebook.com/2050.itorianhttps://www.facebook.com/2050.itorianhttp://twitter.com/itorianhttp://www.itorian.com/