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.

Generic Methods in C#

Hi,

One of the great features of C# is Generic Method. Back in sometime I wrote a Generic Method which serializes or de-serializes an object. The Generic methods are declared with type parameters. So here is the code snippet I wrote some time earlier:

public static void DoSerialization(Stream stream, SerializationType sType, ref T objToUse)
{
try
{
if (objToUse == null)
throw new Exception(“Missing object to serialize/De-serialize”);
XmlSerializer serializer = new XmlSerializer(typeof(T));
if (sType == SerializationType.Serialization)
serializer.Serialize(stream, objToUse);
else if (sType == SerializationType.DeSerialization)
objToUse = (T)serializer.Deserialize(stream);
}
catch (Exception ex)
{ //catching of exceptions
}
}

Let me explain this code. The method takes stream to be de-serialized or serialized depending upon the second argument. SerializationType is enum Type something like

public enum SerializationType
{
Serialization,
DeSerialization
};

and finally the reference of object to serialize or de-serialize. Well let me tell you due to support of type parameter, I was able to make a general function which will serialize or de-serialize any type of object and saved me from re-writing methods for different data type and at the same time its type safe as well 🙂

Isn’t it a great feature. If you do not use Generic Method, start considering them.