Reputation: 1643
I have a GenericListItem object that has a Text and ID property. I am casting various DB objects into List for the purpose of binding to simple generic list controls.
I would like to write an extension method on List that would allow me to specify the relevant properties of T that would get mapped to the Text and ID properties of GenericListItem and then be able to easily convert any List to a list
The signature for the method would need to then somehow accept the two properties of T so I can then output from the list a new List
is something like this possible?
Upvotes: 1
Views: 1562
Reputation: 14581
Instead of reinventing the wheel, you can use Linq:
List<string> list = new List<string>();
list.Add("first");
list.Add("second");
List<ListItem> items = list.Select(s => new ListItem() {Id = s.Length, Text = s.ToLower()}).ToList();
// or if ListItem has a constructor with parameters
List<ListItem> items = list.Select(s => new ListItem(s.Length, s.ToLower()).ToList();
If you really insist on extension, you can wrap the above logic into an extension method, but I don't see the point:
List<ListItem> items = list.ToItemList(s => s.Length, s => s.ToLower());
static class Helper
{
public static List<ListItem> ToItemList<T>(this IList<T> list, Func<T, int> idFunc, Func<T,string> textFunc)
{
return list.Select(s => new ListItem() { Id = idFunc(s), Text = textFunc(s) }).ToList();
}
}
Whatever you choose, don't write a method where you specify properties by name. When you change the name of the properties, compiler will not be able to show you that you have forgotten to update the names in calls to your method, because they are just strings.
Upvotes: 1
Reputation: 8256
public class customList<T> : IList<T>
{
public List<GenericListItem> ToCustomListItem()
{
List<GenericListItem> listItems = new List<GenericListItem>();
//logic to convert list to GenericListItem
}
}
to use do the following
customList<object> list = new customList<object>();
//populate your list
list.ToCustomListItem();
But yes, you can change the names and types as you need to.
Upvotes: 0
Reputation: 144136
I'd create an extension method to convert items, and use that to convert the lists:
public static GenericListItem ToListItem<T>(this T obj, Func<T, string> textFunc, Func<T, int> idFunc)
{
return new GenericListItem
{
Text = textFunc(obj),
Id = idFunc(obj)
};
}
public static List<GenericListItem> ToItemList<T>(this IEnumerable<T> seq, Func<T, string> textFunc, Func<T, int> idFunc)
{
return seq.Select(i => i.ToListItem(textFunc, idFunc)).ToList();
}
Upvotes: 2