Introduction of LINQ:
Abbreviated for Language-Integrated Query (LINQ). It was introduced in Visual Studio 2008 and .NET Framework version 3.5. The main concept behind it was to fill the gap between world of objects and the world of data. LINQ makes a query first-class language construct in C#. The data to be queried can take the form of XML (LINQ to XML), databases (LINQ-enabled ADO.NET: LINQ to SQL, LINQ to Dataset and LINQ to Entities) and objects (LINQ to Objects). LINQ is also highly extensible and allows you to build custom LINQ enabled data providers (e.g.: LINQ to Amazon, LINQ to NHibernate, LINQ to LDAP).
Need & Advantage of LINQ:
- Syntax error for SQL queries are not detected untill runtime, whereas LINQ is integrated into the language.
- XML parsing, iterating, and manipulation is quite tedious, whereas LINQ to XML provides a more powerful and easier-to-use interface for working with XML data, as though it were a database.
- LINQ is not only for querying data but for formatting, validating, and even getting data into the necessary format.
LINQ Syntax:
Query Expression
from int in integers where int>5 select int;
Lambda Expression
integerlist.Where(i => i>5).select(i=>i);
Types of LINQ:
- LINQ to Objects
It enables you to write queries against any collection type that implements an interface called IEnumerable.
- LINQ to XML
It enables you to create, read and write XML based Data.
- LINQ to DataSet
It enables you to write queries against DataSet.
- LINQ to SQL
It provides a run-time infrastructure for managing relational data as objects without losing the ability to query. With the help of which your application is free to manipulate the objects while LINQ to SQL stays in the background tracking your changes automatically.
- LINQ to Entities
It enables you to write queries against the entity framework conceptual model. They are represented by command tree queries, which execute against the object context.
Detail of all above types will be discussed in my next blog.
In this Blog we will discuss Var, IEnumerable and LAMBDA Expressions used with LINQ.
Var Example:
Since Var is anonymous types, hence we can use it whenever we don't know the type of output or it is anonymous. For example:
var q = (from e in Employee join d in Department on e.DeptID equals d.DeptID select new {e.EmpID, e.Name=e.Firstname+" "+e.LastName, d.DeptName});
IEnumerable Example:
IEnumerable<Employee> lst = (from e in Employee where e.City=="DehraDun" select e);
LAMBDA Expression
(Input Parameters) => Method Expression
Assume we have an array of integers and we want to get count of integers greater than 10.
int[] intarray = {2,6,10,44,56,9,3,30};
int count = intarray.count(x => x>10);
If we have list of Users and want to get all active users:
List AllUsers = New List;
List ActiveUsers = AllUsers.Where(u => u.Active == True);
Will discuss more in deep in my upcoming Blog.
So, till then "Happy Coding"
0 Comment(s)