Wednesday 11 February 2009

LINQ Basics

Language Integrated Query is .net 3.0 new features for querying data source where data source is in the form collection of objects. It can be simple array, classes or sql databases.You can say simple "It is general type query language in .net World that can be applied to a variety of data sources."
Advantage of LINQ over conventional query languages(like SQL for databases) has one pattern of coding querying data source. For example Oracle or SQl server, posgres has different syntax of SQL and if one has to query that data sources in their relative syntax, one has to learn the syntax of each data source sql syntax.Other Advantage is of course is highly scalable object oriented code in n- tier Architecture.


LINQ query is executed through foreach statement and foreach statement requires that object that is quried should implement IEnumerable Interface.That is mandatory.so if you query a simple array , it can be queried easily with LINQ as it by default implments IEnumerable interface.All types that implments this interface are called queryable types.


Let start with simple string of array as datasource and execute it through LINQ.I will use Visual studio 2008 for example and i see

using System.Linq; namespace by default in windows forms application.


Open Windows form application. drag & drop Listbox & a button control on form. write this code on button click event.


private void button1_Click(object sender, EventArgs e)

{

String[] MoviesList = new String[] {"Dantes peak","Twister","Shashank redemption","Trueman show","National Treasure" };

var moviesn = from greatmovies in MoviesList

select greatmovies;

foreach (String favMovies in moviesn)

{

listBox1.Items.Add(favMovies);

}

}









Result is shown in screen shot below.




















I will discuss LINQ in depth with LINQ to SQL features later.

2 comments:

  1. I don't see the point...you can omit the entire linq part and the code will work exactly the same.

    ReplyDelete
  2. I know what do you mean but the point was to illustrate the linq link to datasource and process it through linq syntax and not to process datasource itself.Its is simplist example, e.g if datasource was xml you would parse it by xml classes or probably complex sql queries from xml datasource using ADO.net classes but LINQ has much powerful SQL syntax to implement sql queries on a xml source.

    ReplyDelete