Thursday, July 16, 2009

LINQ

C# 3.0 includes many strong new features, but one of the most interesting is the inclusion of its new query keywords, that you use to create Query Expressions. Query Expressions are most commonly associated with Language Integrated Query (LINQ). They're the core syntax that you'll use when you create LINQ queries, whether you use LINQ to Objects, LINQ to SQL, LINQ to XML, or some other custom LINQ provider. I'll discuss the query keywords, how those keywords map to methods defined using the query operands, and how you can define your own custom implementation for the query keywords. The C# team worked to minimize the necessary grammar for LINQ and the associated query syntax. They ended up adding eight contextual keywords to the C# language specifically for query: from, where, select, group, into, orderby, join, and let.

int[] someNumbers = { 2, 3, 7, 11, 13, 17, 19 };
var query = from number in someNumbers

someNumbers is the datasource, and number is the range variable. The datasource must implement IEnumerable, or IEnumerable. In this example, someNumbers implements IEnumerable. The compiler gives the range variable a type to match the type enumerated by the datasource. In the example above, number will be an integer. In general, the range variable is of type T, whenever the datasource implements IEnumerable. In the case where the range variable implements IEnumerable, the range variable is a System.Object. You never need to declare the type of the range variable; the compiler infers it. Consider you have the following string array
string[] names = { "Burke", "Connor", "Frank", "Everett", "Albert", "George", "Harris", "David" };
Task is to take the name which has length greater than 5 and make them capital letter. if we go in normal way we will put a for loop and then call it and assign a temp variable fetch it out hmmm lot of steps lets see how LINQ works on this

LINQ syntax
var query = from s in names where s.Length == 5 select s.ToUpper();

simple rite it looks like T-SQL but in the reverse way don't confused. in T-SQL you know that you are going to query either a table or view but in LINQ you are going to query a object so you dont know from where you are going to query to from comes first instead of select

No comments: