Language Integrated Query (LINQ) is a new component of .NET framework 3.5. It’s main function is to add data querying capabilities to .NET framework using syntax similar to SQL. LINQ integrates the query syntax within .NET programming which makes it possible to access different data sources with the same syntax. We write query expressions to directly manipulate data from different data sources in C# programming language. Let’s see some basic LINQ queries which are required frequently used.
Let’s go through example side by side. We first create the data source as
public class Student
{
public int Id;
public string Name;
public string Address;
}
public class Courses
{
public int StudentId;
public string CourseName;
}
Let’s now add some data to it.
var students = new List<Student>(){
new Student {Id=1,Name=”Ravi”,Address=”Chennai”},
new Student{Id=2,Name=”Arun”,Address=”Chennai”},
new Student {Id=3,Name=”Santosh”,Address=”Chennai”},
new Student{Id=4,Name=”Rahul”,Address=”Chennai”},
};
var courses = new List<Courses>()
{
new Courses{StudentId=2,CourseName=”C#”},
new Courses{StudentId=1,CourseName=”.NET”},
new Courses{StudentId=3,CourseName=”XML”},
new Courses{StudentId=4,CourseName=”Java”}
};
Once our data source is ready. It’s time to do some query. We will look at common queries such as Filtering, Sorting, Join.
Filtering
Filtering means to get only those data which is required based on the given condition. People familiar with SQL statement know it is the where in SQL which does the work of filtering. Here also we have the where clause. for example
var stud = from s in students
where s.Id == 1
select s;
As you can see, how easy it is from the C# programming language to filter the data right from the C# code.
Sorting
Ordering the elements of a sequence based on one or more attributes. The different sorting operators are orderby, orderbydescending,thenby,thenbydescending, and reverse. for example
var stud = from s in students
orderby s.Name
select s;
Join
Joins are used to join objects in one data source with objects that share a common attributes in another data source. The join operators provided in LINQ are join and groupjoin. for our example, we have two data source with studentid as common in both
var stud = from s in students
join c in courses on s.Id equals c.StudentId
select new { s.Name, c.CourseName };
Displaying result
We can use foreach to loop through records and display output or it can be directly bind to the data bind controls.
Example Join
foreach (var sc in stud)
{
Console.WriteLine(“{0} has {1} course.”, sc.Name, sc.CourseName);
}
Example Filter,Sorting
foreach (var s in stud)
{
Console.WriteLine(“Id = ” + s.Id);
Console.WriteLine(“Name = ” + s.Name);
Console.WriteLine(“Address = ” + s.Address);
}