LINQ ( Language Integrated Query)
In C#, Programming with objects means a wonderful strongly typed ability to work with code. You can navigate very much easily through the namespaces, work with a debugger in Visual Studio IDE,and more however, when you have to access data, you will notice that things are dramatically different, i.e. not Strongly typed. And you end up spending most of the time sending strings to the database as commands.
That's why Microsoft developed a new query language name as LINQ (Language Integrated Query) which is developed in .Net 3.5 Framework. It is a new query language very much similar to SQL.
Microsoft has provide LINQ as a lightweight facade that provides a strongly typed interface to the underlying data stores.
Using the LINQ we can write queries on a wide variety of data sources like Array, Collections, Database tables, Data set, XML data. LINQ provides the means for developers to stay within the coding environment they are used to and access the underlying data as Objects that work with IDE,Intelligence and even debugging with LINQ.
Example:-
Before LINQ suppose we have an array of data and we want to find the data through some condition then write so many lines of code after that we get the appropriate data from array. But when LINQ is introduce the it is easy to write the code for finding the data. Let's all these things are show in the example below:-
Ex:- Suppose we have an array and we want to find the data from the array which are greater than 49.
using System;
using System.Linq;
using System.Text;
namespace LINQProject
{
class Program
{
static void Main(string[] args)
{
int[] arr = {33,44,85,94,67,15,28,37,46,97,61,73,13,27};
int count = 0;
for(int i=0;i<arr.Length;i++)
{
if(arr[i]>49)
{
count += 1;
}
}
int[] brr = new int[count];
int index = 0;
for (int i = 0; i < arr.Length;i++ )
{
if(arr[i]>49)
{
brr[index] = arr[i];
index += 1;
}
}
foreach(int x in brr)
{
Console.Write(x + " ");
}
Console.ReadLine();
}
}
}
Output:-
here above the solution without using LINQ. Now i am writing the code using LINQ.
using System;
using System.Linq;
using System.Text;
namespace LINQProject
{
class linq1
{
public static void Main(string[] ares)
{
int[] arr = { 33, 44, 85, 94, 67, 15, 28, 37, 46, 97, 61, 73, 13, 27 };
var brr = from i in arr where i > 49 orderby i select i;
foreach(int x in brr)
{
Console.Write(x + " ");
}
Console.ReadKey();
}
}
}
Output:-
Now you can see the difference the code when we use with LINQ or without LINQ.
Now you can read Linq part 2 Click Here>>>
Now you can read Linq part 2 Click Here>>>
No comments:
Post a Comment