Friday, 6 June 2008

Refactoring: LINQ and Lambda Examples

I had migrated a project from .NET 2.0 to .NET 3.5. Guess it's also a good time to test some simple LINQ and Lambda. :)

Example 1: Simple List<A> to List<B>

List<ItBase> items = new List<ItBase>();

List<DBEntityBase> entities = GetDBEntities(typeof(ItBase), ids);

foreach (DBEntityBase entity in entities)
items.Add((ItBase)entity);

becomes

List<ItBase> items = new List<ItBase>();

List<DBEntityBase> entities = GetDBEntities(typeof(ItBase), ids);

items = entities.ConvertAll<ItBase>(e => (ItBase)e);

Example 2: Return members of List<A> with conditions


List<Attachment> attachments = new List<Attachment>();
foreach (Attachment attachment in this)

{
if (attachment.AttachmentType == attachmentType)
attachments.Add(attachment);
}

return attachments;
becomes

List<Attachment> attachments = new List<Attachment>();

return attachments.FindAll(a => a.AttachmentType == attachmentType);

Example 3: from array of int (index) returns List<Y> objects
List<ItBase> items = new List<ItBase>();

foreach (int id in ids)

{
items.Add(this[id]);
}

return items;
becomes

List<ItBase> items = new List<ItBase>();

items.AddRange(from i in ids select this[i]);
return items;

Example 4: From List<A> to List<B> but A and B are not inherited classes

List<User> users = new List<User>();

foreach (UserData userData in result)
{
User user = new User();
user.Email = userData.Email;
user.ID = userData.ID;
user.Name = userData.Name;
users.Add(user);
}
becomes

List<User> users = new List<User>();

users = result.ConvertAll<User>(r =>
new User
{
Email = r.Email,
ID = r.ID,
Name = r.Name,
}
);


2 comments:

  1. Yep very good. I particularly liked the last one for converting a list of objects from one type to another. In my case I want to convert the results of two different stored procedure calls into a common format. The last example holds promise for that I reckon.

    Thanks, David :-)

    ReplyDelete