LINQ to SQL, LINQ to XML and Accessing DataTable using LINQ

No.of Views1313
Bookmarked0 times
Downloads 
Votes3
By  kirtan007   On  28 Jun 2010 07:06:55
Tag : LINQ , General
This article demonstrates how to use LINQ on DataTable, XML Data using LINQ to XML and SQL server data base using LINQ to SQL Classes.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

In this article I will show you how to access basic data sources like Data Table, SQL server database using LINQ to SQL Classes and XML data using LINQ to XML.

Technologies

C# 3.5/4.0

Implementation

I will introduce the LINQ first for the Beginners who are working first time with the LINQ.LINQ is Language integrated Query that is used to query on Data Source Objects like Arrays Collection Datasets etc .For example we can select some data based on some criteria from DataTable, We can select some Elements from array.

Now I think you are familiar with the basic purpose of the LINQ. So let's learn basic syntax of LINQ query.LINQ query's syntax is somewhat similar to the Structured Query language. So if you are familiar with the SQL syntax it will be very easy to understand for you.

Query starts with 'from' keyword and ends with 'select'.

from <ELEMENTNAME> in<DATA_SOURCE_NAME> where <YOUR_CONDITION_ON_DATA> select <ELEMENT_NAME>

Where element name is name of object which you are retrieving from data Source condition can be anything according to Element Type you are receiving from Data Source.

In sample code below I will show you sample code in which we will see how to access elements from array, Collection and DataTable.

Basic Steps I have done in Sample Application are as below

  1. Created Some Sample Data Sources (Created DataTable, SQL Database and One XML File)
  2. Accessed each with LINQ
static void Main(string[] args)
        {/*************************************************
* Creating DataSources for Manipulating by LINQ
*************************************************/
//Build DataTableDataTable dt = new DataTable(); dt.Columns.Add("Fruite"); dt.Columns.Add("Color");//Add Few Rows to DataTableDataRow dr = dt.NewRow(); dr[0] = "Orange"; dr[1] = "Orange"; dt.Rows.Add(dr); DataRow dr1 = dt.NewRow(); dr1[0] = "Apple"; dr1[1] = "Red"; dt.Rows.Add(dr1); DataRow dr2 = dt.NewRow(); dr2[0] = "Banana"; dr2[1] = "Yellow"; dt.Rows.Add(dr2); DataRow dr3 = dt.NewRow(); dr3[0] = "Cherry"; dr3[1] = "Red"; dt.Rows.Add(dr3);/*
***********************************
Accessing DataTable using LINQ
**********************************
*/
//Select Elements Where color is red IEnumerable<DataRow> TableData = from e in dt.AsEnumerable() where e[1].ToString() == "Red" select e;//print the ResultConsole.ForegroundColor = ConsoleColor.Red; Console.WriteLine("\n\n************Filtered Data From DataTable using LINQ*******\n\n"); Console.ForegroundColor = ConsoleColor.White;foreach (DataRow row in TableData) { Console.WriteLine(String.Format("{0} {1}",row[0],row[1])); }/* ***************************************
* Access XML Document using LINQ
* ***************************************/
Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("\n\n***********Access XML Document using LINQ ******************\n\n"); Console.ForegroundColor = ConsoleColor.White;//Find the books in XML file which belongs to Genre Computer var CompuData = from e in XElement.Load("XMLFile1.xml").Elements("book") where e.Element("genre").Value.ToString() == "Computer" select e;// Print the Result of LINQ Query foreach (var obj in CompuData) { Console.WriteLine(obj); }/**************************************
* Access SQL Database using LINQ
* *************************************/
Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("\n\n*************** LINQ -> SQL *********************\n\n"); Console.ForegroundColor = ConsoleColor.White;//Print Data in Table to ScreenDatabase1DataContext db = new Database1DataContext(); var UserData = from u in db.UserDatas select u;foreach (var x in UserData) { Console.WriteLine(x.ID+" "+x.Username+" "+x.Password); } Console.ReadKey(); }

 Explanation of the Code

First we are creating some data sources Data Table using simple C# code.We created a Data Table in which we have added two data Column and added 4 rows to it

//Select Elements Where color is redIEnumerable<DataRow> TableData = from e in dt.AsEnumerable() where e[1].ToString() == "Red" select e;//print the ResultConsole.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("\n\n************Filtered Data From  DataTable using LINQ*******\n\n");
            Console.ForegroundColor = ConsoleColor.White;foreach (DataRow row in TableData)
            {
                Console.WriteLine(String.Format("{0} {1}",row[0],row[1]));
            }

 In above code we are accessing DataTable till now we were working with String type so we were using IEnumerable<string> but here we are dealing with DataTable that is consist of the DataRow type so we will get result in IEnumerable<DataRow> object . Here in result we want rows in which color column value is 'Red'.

So we placed condition e[1].ToString() == 'Red' and rest of thing as it is.

Now lets understand second part  accessing XML Data using LINQ

Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n\n***********Access XML Document using LINQ ******************\n\n");
Console.ForegroundColor = ConsoleColor.White;
 
 //Find the books in XML file which belongs to Genre Computervar CompuData = from e in XElement.Load("XMLFile1.xml").Elements("book") where e.Element("genre").Value.ToString() == "Computer" select e;
 
// Print the Result of LINQ Queryforeach (var obj in CompuData)
  {
       Console.WriteLine(obj);
  }

 

In above code we have selected Book Elements from the XML file and the filtered the book elements those who re having genre == Computer and printed the result on the screen.

and Finally by below code we are accessing the SQL  Database Table using LINQ.

Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("\n\n*************** LINQ -> SQL *********************\n\n");
            Console.ForegroundColor = ConsoleColor.White;//Print Data in Table to ScreenDatabase1DataContext db = new Database1DataContext();
 
            var UserData = from u in db.UserDatas select u;foreach (var x in UserData)
            {
                Console.WriteLine(x.ID+" "+x.Username+" "+x.Password);
 
            }

 

For working with above code we need to prepare a Database and LINQ -> SQL Classes first then we can use this code ..lets se how to do that first.I created Database1.mdf from Solution Explorer and in the database I created one table called userData for demo purpose and added some records.

 

Image Loading

Now after building database we need to create LINQ->SQL Classes for that we will add class by going to Solution Explorer >> Right Click Solution and add LINQ to SQL Classes. 

Image Loading

After that we need to create the classes that thing we will do using Graphical Editor Provided by visual studio. 

Image Loading

Now you can do the code that I have mentioned above.That's it. You have successfully leant how to use LINQ with DataTable XML Data and SQL Server Database using LINQ to SQL classes.

Conclusion

Article demonstrates how to use LINQ with DataTable, XML Data using LINQ to XML and SQL server data base using LINQ to SQL Classes.

Sample Project Source

Download source files -334 kb

 
Sign Up to vote for this article
 
About Author
 
kirtan007
Occupation-
Company-
Member Type-Senior
Location-Not Provided
Joined date-02 Jul 2009
Home Page-http://kirtan.uni.cc
Blog Page-
He completed his Bachelor of Computer Application from Gujarat University 2009 .He is doing Master of Computer Application from Gujarat Technological University right now .. His area of Interests are Web Hacking , C# .net Windows form ,asp.net , WPF ,Silverlight ,SQL Server and Some PHP.
 
 
Other popularSectionarticles
    Deferred Execution executes the query only when Loop starts. What I mean here is that, we iterate through the query variable to get the result.
    Published Date : 15/Jan/2011
    In this article we will focus LINQ Remote and Local exaction such as This query executes on the server, Remote execution of query is default in LINQ, In Remote execution advantage of Databases index can be taken, Remote execution allows us to take the advantage of Database server engine, Remote execution allows us to only select particular rows from the table. This is very useful when we do have large amount of data in the server.
    Published Date : 07/Jan/2011
    In this article, we will see how to work with LINQ against IIS.
    Published Date : 10/Aug/2010
    how to create a XML tree using Functional Construction method of LINQ to XML.
    Published Date : 13/Apr/2010
    In this article we will focus, how to read CSV file using LINQ to CSVProvider.I hope we know read CSV file using StreamReader or any other readers in C#. But when we are use the LINQ to CSVProvider, and then we could get additional features to query data in LINQ as like Sql Query.
    Published Date : 01/Jan/2011
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top