04 June 2010

LINQ to Dataset

LINQ to Dataset enables you to query and update data in to ADO.NET dataset. Once the data is cashed to client side we can use this functionality to query against that. Your application typically needs to search, filter thru this data in order to display this data according to the need. Data View provides a very limited options .when it comes to creating a filtered view of the data. LINQ extends these capabilities to a greater extend.For Three tires as well as N tier architecture LINQ will be very good option as dataset is coming on middle tier and UI or client can query using LINQ. Please see the diagram below:

Well, let’s describe the solution with an example. Suppose we have following two tables containing data in the database.

Prerequisite:  Both this table is loaded to a data set called ds now we will try to run some sample LINQ quires to pull put the data. We will start with a simple Query.

var results = from customer in customersvar customers = ds.Tables["Customer"].AsEnumerable();
              orderby customer.Field("Name")
              select customers;
dataGridView1.DataSource = results.AsDataView();
We can also do join operations too. A sample query is given below.
var customers = ds.Tables["Customer"].AsEnumerable();
var orders = ds.Tables["Order"].AsEnumerable();
var results = from customer in customers
                    join order in orders
                      on order.Field("CustomerID")
                         equals customer.Field("Customer")
                           into custOrders
              select customers;

Now we will populate a grid from this.
dataGridView1.DataSource = results.AsDataView();
As we specified on earlier blog apart from all these we can have 
Restriction
Where
Projection
Select,Selectmany
Ordering
OrderBy, ThenBy
Grouping
GroupBy
Quantifiers
Any,All
Partitioning
Take,Skip
Sets
Distinct,Union,Intersect,Except
Elements
First,ElementAt,FirstorDefault
Aggregation
Count,Sum,Iin,Max,Avarage
Conversion
ToArray,ToList
Casting
OfType(T)

All the examples given above is just the tip of iceberg on what you can do with LINQ and Lambda expressions. There is tons of samples and articles available on Internet on this, if you are looking for a way to simplify and speed up your business processing logic in your middle tier, LINQ is something you need to adopt!

No comments: