What LINQ Is
Language-Integrated Query (LINQ) is a powerful query language introduced with .Net 3.5 & Visual Studio 2008. LINQ can be used with C# or Visual Basic to query different data sources.
LINQ stands for Language Integrated Query, and is a way of providing a general purpose "querying" mechanism in the CLR.Instead of writing another query language, MS language developers provided a way to express queries directly in their languages (such as c# and vb) means you can write queries directly in your code. It operates across a broad spectrum of data sources (SQL databases, in-memory representations, XML, etc.).
Why Do We Need Linq
Most of the Applications are based on Relational Database. So there is always object is needed for database Connection.
1 ) All the data needed in an application are not stored in the same source. The source could be a relation database, some business object, XML file, or a web service.
2. ) Accessing in-memory object is simpler and less expensive than accessing data from a database or XML file
3. ) The data accessed are not used directly, but needs to be sorted, ordered, grouped, altered etc.
Hence if there is one tool that makes all kind of data access easy that allows joining data from such disparate data sources and perform standard data processing operations, in few lines of codes, it would be of great help. Linq overcomes all the problems .
Example
Namespace Required - using System.Linq;
using System;
using System.Linq;
class LinqExp
{
static void Main()
{
string[] words = {"India", "wonderful", "Country", "Amazing", "world"};
//Get only short words
var shortWords = from word in words
where word.Length <= 5
select word;
//Print each word out
foreach (var word in shortWords)
{
Console.WriteLine(word);
}
Console.ReadLine();
}
}
OutPut –
India
world
Linq Syntax
There are two syntaxes of LINQ which are mentioned below.
Query Syntax
var highestLength = from w in words where w.length <= 5;
LINQ query can be applied to any data-bearing class that inherits from IEnumerable<T> .
Lamda Syntax
var highestLength = words.Where( w => w.length > 10);
LINQ Types
1. ) LINQ To Objects
2. ) LINQ To XML
3. ) LINQ TO DataSet
4. ) LINQ To SQL
5. ) LINQ TO Entities
Advantage Of LINQ
1. ) Developers don’t have to learn a new query language for each type of data source or data format.
2. ) LINQ makes the code more readable so other developers can easily understand and maintain it.
3. ) It reduces the amount of code to be written as compared with a more traditional approach.
4. ) It provides type checking of objects at compile time.
5. ) LINQ provides IntelliSense for generic collections.
0 comments:
Post a Comment