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.