Sunday, 17 January 2010

Lambda Expression Series 1:

This is a really interesting one this one I used in on of my Live project the question was when we converting List of one object to another List of object why we use foreach loop they must some other way we can achieve in less line of code and more efficient. I start studying Lamba Expressions and come to this point and get the answer in ‘Yes’. Here is the Demo:

Consider the class Registration and RegistrationDC. Our goal here is to convert List<Registration> to List<RegistrationDC> the classes are:

public class Registration

{

public int RegistrationId { get; set; }

public string FirstName { get; set; }

public string LastName { get; set; }

public string EmailAddress { get; set; }

public string Mobile { get; set; }

}

And

public class RegistrationDC

{

public int RegistrationId { get; set; }

public string FirstName { get; set; }

public string LastName { get; set; }

public string EmailAddress { get; set; }

public string Mobile { get; set; }

}

Now the on traditional way we will convert the list to other list bu using ForEach loop so this is the method:

private List<RegistrationDC> ConvertRegistrationToRegistrationDC(List<Registration> list)

{

List<RegistrationDC> listDC = new List<RegistrationDC>();

foreach (Registration reg in list)

{

listDC.Add(new RegistrationDC(reg.RegistrationId,reg.FirstName,reg.LastName,reg.EmailAddress,reg.Mobile));

}

return listDC;

}

But the simplest and efficient way using Lamda Expression is:

private List<RegistrationDC> ConvertRegistrationToRegistrationDC_WithLAMBDA(List<Registration> list)

{

var listDC = list.Select(reg => new RegistrationDC(reg.RegistrationId,reg.FirstName,reg.LastName,reg.EmailAddress,reg.Mobile));

return new List<RegistrationDC>(listDC);

}

I ran both in console application with time difference and there is not much effeiciency in both approaches if we have few members is list but if we are talking about 100s or 1000s than Lambda expresion approach is more effecient but I still want to raise a point here that as far as debugging is concern foreach approach is easy to debug but it all depends.

Thanks to all if any question or comment please post it.




No comments: