query datasets using linq to dataset

Using LINQ to DataSet, a programmer can query datasets. We know DataSet is a in-memory representation of data and is used extensively in database applications. Using the DataAdapter, the dataset is filled with data. After the data is filled, we can perform queries on the data. LINQ to DataSet queries can be constructed in the following two ways. One is query expression syntax and other is method-based query syntax.

These queries are the fastest executing queries on datasets and can be written using the programming language using vb.net and c#. The first step in using these queries is to populate the datasets and query it and functionality can be used through the methods of DataRow Extension and DataTableExtension classes. Observe that the query pattern is similar to any other query. The below query executes only when we iterate over the query using foreach loop.

using System; 
using System.Collections.Generic; 
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace LinqExamples
{    
public partial class LINQtoDataSet : Form
{    
	string connectionString = "Data Source=LocalHost; Initial CataLog=ERPFinAccounting;
     User ID=kris; 	Password=rooman123";
	SqlConnection myConnection;
	string str_Account_Select = "SELECT * FROM AccountsTable";
	SqlCommand myCommand;
	SqlDataAdapter myAdapter;
	DataSet myDataSet;
    private void LINQtoDataSet_Load(object sender, EventArgs e)
    {   //Instantiate the Connection object
		myConnection = new SqlConnection(connectionString);	
        myConnection.Open();
        myCommand = new SqlCommand(str_Account_Select, myConnection);
        //Instantiate  DataSet object
		myDataSet = new DataSet();		
        myAdapter= new SqlDataAdapter();
        //Set DataAdapter command properties	  			
		myAdapter.SelectCommand = myCommand;
        //Populate the Dataset   		
		myAdapter.Fill(myDataSet, "AccountsTable");
        DataTable accounts = myDataSet.Tables["AccountsTable"];
   		var query =
           		from o in accounts.AsEnumerable()
           		where o.Field("AccountName")== "Account1" 
           		select o;
           		listBox1.DataSource = query.ToList();
           		listBox1.DisplayMember = "AccountName";
   }    
}
}