Just created profile on SlideShare.NET

I have just created an account on SlideShare.NET which will help me uploading and sharing presentation slides of events that take place 🙂

You can visit my profile on SlideShare.NET or download/view from the widget below!

SlideShare

Enjoy!!!
http://www.slideshare.net/adil.mughal/presentations

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.

Real World Scenario: Month Based Selection using AJAX Calendar Extender

Often we get requirement of enabling only month based selection in calendar control in which a calendar should display only month instead of dates or you can say a calendar that allow users to pick month only. This can be achieved by manipulating functionality of AJAX Calendar extender using JavaScript.

First, you need to set the behaviorID property of Calendar extender control and add two event handler “OnClientHidden” and “OnClientShown”. For instance,

<asp:TextBox ID="txtDate" runat="server" ReadOnly="false" onfocus="AjaxDateOnFocus(this);" Width="60px" onblur="AjaxDateOnBlur(this);" />
<
cc1:CalendarExtender ID="ctxtDate" runat="server" TargetControlID="txtDate" Format="MMM-yyyy" OnClientHidden="onCalendarHidden" OnClientShown="onCalendarShown" BehaviorID="calendar1" />

Now use the following JavaScript with respective BehaviorID

function onCalendarShown() {
var cal = $find("calendar1"); //Setting the default mode to month
cal._switchMode("months", true); //Iterate every month Item and attach click event to it
if (cal._monthsBody) {
for (var i = 0; i < cal._monthsBody.rows.length; i++) {
var row = cal._monthsBody.rows[i];
for (var j = 0; j < row.cells.length; j++) {
Sys.UI.DomEvent.addHandler(row.cells[j].firstChild, "click", call);
}
}
}
}

function onCalendarHidden() {
var cal = $find("calendar1");
//Iterate every month Item and remove click event from it
if (cal._monthsBody) {
for (var i = 0; i < cal._monthsBody.rows.length; i++) {
var row = cal._monthsBody.rows[i];
for (var j = 0; j < row.cells.length; j++) {
Sys.UI.DomEvent.removeHandler(row.cells[j].firstChild, "click", call);
}
}
}
}

function call(eventElement) {
var target = eventElement.target;
switch (target.mode) {
case "month":
var cal = $find("calendar1");
cal._visibleDate = target.date;
cal.set_selectedDate(target.date);
cal._switchMonth(target.date);
cal._blur.post(true);
cal.raiseDateSelectionChanged();
break;
}
}

That’s all 🙂 and your calendar extender will now look like

image

Enjoy!

Please note that the script is partially taken from AghaUsman.net