简体   繁体   中英

Pass Object properties as parameters into Generic List Extension method

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?

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();
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM