Hello LINQ

In Microsoft Pakistan Developers Conference (PDC) 2007, I attended a sessions on Language Integrated Query (LINQ) but until recent I didn’t utilize it seriously. But recently I go through some videos on LINQ at MSDN. I was impressed at all 🙂

LINQ is used to query data from objects. There are three basic categories of LINQ:

  • LINQ to Objects
  • LINQ to XML
  • LINQ to SQL

If you are new to LINQ, I would recommend to skim through article on LINQ on MSDN. Let’s see a simple example of LINQ to Objects. LINQ to Objects is used to query in-memory data stores. Suppose we have a collection of countries’ name and we want to get list of countries starting with ‘C’.

string[] countriesCollection = 
{ "Pakistan", "India" , "UAE", "US", "Australia", "UK", "Canada",
"China"};

Without LINQ, we need to traverse the list and manually add a check on each string. LINQ do that for me in a simpler way:

var queryResult = from country in countriesCollection
                  where country.StartsWith("C")
                  orderby country
                  select country;

Now simply print the list return, ordered, in queryResult

foreach (var item in queryResult)
    Console.WriteLine(item.ToString());

The ouput will comprise of two items:

Canada
China

Similarly, we can query to not only primitive data types but also custom data types as well. For instance, let’s say we have a class Student as shown below:

public class Student
{
    public string Name { get; set; }
    public int Id { get; set; }
    public string Grade { get; set; }
    public Student(string stName, int stId, string stGrade)
    {
        Name = stName;
        Id = stId;
        Grade = stGrade;
    }
}

Let’s create a List of student type and manually feed some data to it. After that we will query to get all the student having grade B:

List studentsList = new List();
studentsList.Add(new Student("Adil", 1, "A"));
studentsList.Add(new Student("Sami", 10, "B"));
studentsList.Add(new Student("Faisal", 100, "B"));
var query = from student in studentsList
            where student.Grade == "B"
            select student;

Printing result in query will be

Sami
Faisal

In short, LINQ to Objects allows us to query in memory objects not just on primitive data types but also on our custom data types and provide an ease to developer for querying data from in memory objects.