02 June 2010

LINQ to Collection

Language-Integrated Query (LINQ) is an innovation introduced in Visual Studio 2008 and .NET Framework version 3.5 that bridges the gap between the world of objects and the world of data. It is Microsoft First step to Object Data Model. The data can live inside XML documents, inside relational database tables, or inside collections of objects. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support. Also, we might have to learn a different query language for each type of data source: SQL/Oracle databases, XML documents. With the introduction of LINQ it is possible to write these quires in our native Languages.LINQ will premier in Visual Studio 2008, and will become the next must–have skill for .NET developers.
 Microsoft designed LINQ to provide general-purpose query facilities to the .NET platform. More specifically, LINQ defines a set of standard query operators in the System. Linq namespace to select, filter, aggregate, and partition data from any type that implements the IEnumerable or IEnumerable interfaces. The standard query operators are compliant with the Common Language Specification (CLS) and work inside any .NET language that supports generics. The below figure describes the relationship between LINQ, LINQ enabled data sources and Languages that support LINQ.
By using LINQ you can query and transform the data in:
1. XML Document
2. SQL Databases
3. ADO.NET Datasets
4. NET Collections 
Lets take a ride in to all these.Take a very simple example of a small string collection and how to make a LINQ query to this:
private void SimpleLinqQuery()
{
//Simple LINQ query
string[] FAMTeam = { "Jijo", "Srini", "Vijay", "Palani",
"Geetha", "Melvin", asad","Sheldon","Sandeep",
"Rao","Sudeep", "Raveen"                                  };
var list = from b in FAMTeam
orderby b ascending
select b;

StringBuilder sb = new StringBuilder();
foreach (string s in list)
{
sb.Append(s + Environment.NewLine);
}
MessageBox.Show(sb.ToString(), "FAM Team");
}
Now lets take out a query and see what is inside.Here we are strting our query with from.Observe the differnce between traditional quries.In order to support LINQ Microsoft add new feature of Anonymous Types.This make it possible for the compiler to generate the equivalent of the customer class for you based on the query.Structure of a LINQ Query.
A LINQ Query (or query expression) contains combination one clauses that specify data sources and iteration variables for the query. The Query expression can also include optional clauses that specify instruction for:.
• Filtering
• Sorting
• Grouping
• Joining
• Calculating
The query expression always starts with FROM CLAUSE. This clause identifies the source of the data, and the variables that the query uses to iterate over the data source. After FROM clause, you can include any of the additional clauses that filter, sort, and so on  Also see the flexibility of some query operations:
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)

Now let’s take another example. We can create a class something like this.
public class Contact
{
   public string Name { get; set; }
   public string Designation { get; set; }
   public Contact(string name, string designation)
   {
     this.Name = name;
     this.Designation = designation;
   }
}
Now we can populte this as list and query the list with LINQ and populate a Data grid.
 private void LinqToCollectionQuery()
{
    List contacts = new List();
    contacts.Add(new Contact("Jijo", "Software Engineer"));
    contacts.Add(new Contact("Sudeep", "Program manager"));
    contacts.Add(new Contact("Srini", "Architect"));
    contacts.Add(new Contact("Archana", "Tester"));
    contacts.Add(new Contact("Vishal", "Tech Lead"));
    contacts.Add(new Contact("Sheldon", "Project Manager"));
    contacts.Add(new Contact("Vijay", "Project Lead"));
    var listContacts = from b in contacts
                       orderby b.Designation
                       ascending
                       select b;
   _contactDataGrid.ItemsSource = listContacts.ToList();
}
This is going to be a simple ground level work.For those who really wants to do indepth options of query will be available on detailed study.We will move ahead for the other options on next blogs.

No comments: