The LINQ Way

In this post, I will be sharing some code snippets to continue emphasizing on the use of LINQ. The code is almost the same which I discussed in Emerging .NET Devs UG Meeting in Oct ‘09.

Let’s see a comparison of doing similar task with typical way and the LINQ way, in particular related to LINQ to Object, but first consider interface “ICustomer” on which we are going to play

namespace LinqToObject
{
internal interface ICustomer
{
string CustomerID { get; set; }
string CompanyName { get; set; }
string ContactName { get; set; }
string Country { get; set; }

List<Customer> GetCustomers();
}
}

Now assume there is a class Customer implementing ICustomer and what we want is to retrieve list of all customers in country “Pakistan”.

Typical Way:

public IEnumerable<ICustomer> GetCustomersFromPakistan()
{
List<ICustomer> customerList = new List<ICustomer>();
foreach (Customer c in customer.GetCustomers()) //customer is Customer:ICustomer
{
if (c.Country.StartsWith("Pakistan"))
customerList.Add(customer);
}
return customerList;
}

and it will happily print list of all customers from Pakistan

The LINQ Way:

public IEnumerable<ICustomer> GetCustomersFromPakistan()
{
var result = from c in customer.GetCustomers()
where c.Country.StartsWith("Pakistan")
select c;
return result;
}

Remarks: To be honest, it is a bit clean but nothing very impressive right?

So let’s add a further requirement, now I want all CustomersFromPakistan but ordered by Customer ID. Let’s compare the code again.

Typical Way:

public IEnumerable<ICustomer> GetCustomerFromPakistanList()
{
List<ICustomer> list = new List<ICustomer>();
foreach (ICustomer c in customer.GetCustomers())//customer is Customer:ICustomer
{
if (c.Country.Contains("Pakistan"))
{
list.Add(customer);
}
}
list.Sort(delegate(ICustomer customer1, ICustomer customer2)
{
return customer1.CustomerID.CompareTo(customer2.CustomerID);
});

return list;
}

The LINQ Way:

public IEnumerable<ICustomer> GetCustomersFromPakistan()
{
var result = from c in customer.GetCustomers()
where c.Country.Contains("Pakistan")
orderby c.CustomerID;
select c;
return result;
}

Remarks: What do you say? it’s clean and simple right!!!

Further with the use of Lambda expression, you can filter out lists easily. For instance,

ICustomer customer = new Customer();
var list = customer.GetCustomers()
.Where<ICustomer>(c=> c.Country == "Pakistan");
“Where” is an extension method and will provide you a simple way to filter sequence of values based on predicate defined using lambda expression.

Summary:

As you will come across complex conditions, for loops are really messy and LINQ provides a clean and simple way to perform object manipulation that will also improve productivity of developer. If you are still not using LINQ, I recommend you to get some hands on, you will really enjoy it.

Event Summary: Oct UG Meeting on LINQ

I participated as speaker along with Munir Usman (MVP) in Emerging .NET DevsOctober UG Meeting on LINQ. I was excited as I was speaking after couple of months 🙂 The event was organized by  Emerging .NET Devs. We tried to make the event as interactive as possible. The style of discussion was comparison between approaches before and after LINQ and how LINQ makes life of programmer easy and increase productivity. 

Adil and MunirDSC01643

Following was the agenda of the discussion:

  • Challenges before LINQ

  • Introduction to LINQ

  • Pre-requisite to LINQ (C# 3.0 Features)

  • LINQ to Objects

  • Refreshment

  • LINQ to SQL

  • LINQ to XML

For more details about the events, please visit Emerging .NET Devs – Oct UG Meeting Summary. Also, those who attended the show, please provide feedback about the event here. Thank you everyone for attending the show.

I will be speaking on LINQ

Hello, I’m excited to share with you all that finally, after couple of months, I will be speaking on LINQ at the Emerging .NET DevsOctober Monthly meeting on 17th Oct at Microsoft Innovation Center.

We will talk on some of the challenges developers were facing before LINQ and how LINQ help us in querying, sorting and filtering data. The event is free and seats are limited. So hurry up and get yourself registered. For details about the event or registration, please visit http://eDotNetDevs.org.

Below is the map of Microsoft Innovation Center, which is located at FAST-National University, City Campus.

View Microsoft Innovation Center, Karachi in a larger map

Using LINQ with Relational Data

Greetings,

Till this point we have seen LINQ To Objects and LINQ To XML. I found a great webcast on using LINQ with Relational Data by Rob Bagby, So I thought instead of explaining my way, I would recommend you to go through the webcast 🙂

MSDN Webcast: Using LINQ with Relational Data (Level 100)

LINQ To XML

In my earlier post on LINQ, we saw an example of LINQ to Objects. In this post we will see LINQ to XML example. LINQ to XML was the real reason why i attracted towards LINQ. I’m pretty excited to see what LINQ provides as compare to the old techniques. So let’s start coding 🙂

Let’s say we have an XML as below:











Now suppose that I want to get list of all employees in Microsoft. Without LINQ, I would probably load the xml in XmlDocument object and then apply XPATH with respect to the company name attribute. With LINQ, it’s easy and simple way to load xml and write a single SQL like query even for XML. For instance i want to fetch list of all employees in KalSoft,

var companies = XElement.Load("companies.xml").Elements("Company");

var queryResult = from company in companies
where company.Attribute("Name").Value == "KalSoft"
select company.Descendants();

This query selects all the descendants i.e. Employee(s) of company having Name == “KalSoft”. To obtain the output we can get the string as

foreach (var item in queryResult)
{
foreach (var element in item)
{
Console.WriteLine(element);
}
}

which will give us the desired output:

LinqToXmlOutput

Hence, LINQ to XML provides an simpler way, to programmer, to query XML Documents based on different conditions.

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.