What is LINQ? Learn it by solving problems.
Introduction
LINQ (Language INtegrated Query) fills the
gap between programming languages and database.
According to Anders Hejlsberg (C# Chief
Architect):-
“Microsoft’s original motivation behind
LINQ was to address the impedance mismatch between programming languages and
database.”
If we compare LINQ to SQL, LINQ is simpler,
tidier and very handy to use. It’s rather like comparing C# to C/C++
Programming, the time is gone when C/C++ was best but now coder needs something
special like LINQ and it’s a big win. SQL is a very old language that was
invented about 1974. Since then it's been extended endlessly, but never
redesigned. This has made the language messy. You might have become so
accustomed to this that you can't see anything wrong.
I think my above lines will increase your
concrete knowledge about Microsoft LINQ, so let’s look at some problems and we
will solve this using LINQ and non-LINQ.
Question: We have a collection of Student
objects and we want to find out three students who have minimum age.
Look at the non-LINQ Solution:-
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void
Main(string[] args)
{
// create the object of the class and assigning
values
Student[] std = {
new Student
{ Name = "Abhimanyu", Age = 21 },
new Student
{ Name = "Deepak", Age = 10 },
new Student
{ Name = "Mahtab", Age = 15 },
new Student
{ Name = "Ravi", Age = 12 },
new
Student { Name =
"Avnish", Age = 13 }
};
// define the array to hold the results
Student[] results =
new Student[3];
// short the contents of the array
Array.Sort(std, (student1, student2)
=> {
return
Comparer<decimal>.Default.Compare(student1.Age,
student2.Age);
});
// get the first three students in the array as
the results
Array.Copy(std, results, 3);
// print out the name
foreach (Student
s in results)
{
Console.WriteLine("Name: {0}, Age: {1}", s.Name, s.Age);
}
Console.ReadKey();
}
}
//class
class
Student
{
public string
Name { get; set;
}
public int Age {
get; set; }
}
}
Now by using LINQ we can significantly
simplify the querying process, look at example below.
using System;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void
Main(string[] args)
{
// create the object of the class and assigning
values
Student[] std = {
new Student
{ Name = "Abhimanyu", Age = 21 },
new Student
{ Name = "Deepak", Age = 10 },
new Student
{ Name = "Mahtab", Age = 15 },
new Student
{ Name = "Ravi", Age = 12 },
new
Student { Name =
"Avnish", Age = 13 }
};
// using LINQ
var results =
from s in std
orderby s.Age
ascending
select new
{
s.Name, s.Age
};
int count = 0;
// print the name
foreach (var
a in results)
{
Console.WriteLine("Name: {0}, Age: {1}", a.Name, a.Age);
if (++count == 3)
{
break;
}
}
Console.ReadKey();
}
}
//class
class Student
{
public string
Name { get; set;
}
public int
Age { get; set;
}
}
}
Remember to add a namespace using
System.Linq.
Comments
Post a Comment