Introduction
This is a useful extension method for collections to convert an object collection in a single line of code.
Background
The goal of this example is to bring a developer an easy way to convert an object collection between different object types.
Using the Code
Add the convertor method to your project.
Using one line of code, you can convert one object collection type to another.
Instantiate the delegate using an anonymous method inline:
public static IEnumerable<TConvertedObject> Convertor<TObjectToConvert, TConvertedObject>
(this IEnumerable<TObjectToConvert> collection, Func<TObjectToConvert
, TConvertedObject> converter)
{
return new List<TObjectToConvert>(collection)
.ConvertAll<TConvertedObject>
(delegate(TObjectToConvert from)
{
return converter(from);
});
}
Example
public class Person
{
public long Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
public class PersonItem
{
public long Id { get; set; }
public string Name { get; set; }
}
IList<Person> personCollection = new List<Person>();
personCollection.Add(new Person { Id = 1, Name = "shay", Address = "isr" });
personCollection.Add(new Person { Id = 2, Name = "pap", Address = "isr" });
Func<Person,PersonItem> convert = (p) => new PersonItem{ Id = p.Id, Name = p.Name };
IEnumerable<PersonItem> personItemCollection =
personCollection.Convertor<Person, PersonItem>(convert);
Points of Interest
Wrapping up the List ConvertAll method.
History
- 19th April, 2008: Initial post