简体   繁体   中英

Lambda Extension Method for Converting IEnumerable<T> to List<SelectListItem>

I need a way to create an extension method off of an IEnumerable that will allow me to return a list of SelectListItem's.

For example

    public class Role
    {
        public string Name {get;set;}
        public string RoleUID {get;set;}
    }
    IEnumerable<Role> Roles = .../*Get Roles From Database*/
    var selectItemList = Roles.ToSelectItemList(p => p.RoleUID,r => r.Name);

this would give me a SelectItemList with the Name being the display, and the RoleUID being the value.

I want this to be generic so I can create it with any two properties off of an object, not just an object of type Role. 我希望这是通用的,因此我可以使用对象的任何两个属性创建它,而不仅仅是Role类型的对象。

How can I do this?

I imagine something like the following

 public static List<SelectItemList> ToSelectItemList<T,V,K>(this IEnumerable<T>,Func<T,V,K> k)

or something, I obviously know that would be incorrect.

Why not just combine the existing Select and ToList methods?

var selectItemList = Roles
  .Select(p => new SelectListItem { Value = p.RoleUID, Text = p.Name })
  .ToList();

If you want to specifically put it into one method then you could define ToSelectListItem as a combination of those two methods.

public static List<SelectListItem> ToSelectListItem<T>(
  this IEnumerable<T> enumerable,
  Func<T, string> getText,
  Func<T, string> getValue) {

  return enumerable
    .Select(x => new SelectListItem { Text = getText(x), Value = getValue(x) })
    .ToList();
}

How about something like this? (note: I haven't tested this, but it should work.

    public static List<SelectListItem> ToSelectItemList<T>(this IEnumerable<T> source, Func<T, string> textPropertySelector, Func<T, string> valuePropertySelector, Func<T, bool> isSelectedSelector)
    {
        return source
            .Select(obj => new SelectListItem
            {
                Text = textPropertySelector(obj),
                Value = valuePropertySelector(obj),
                Selected = isSelectedSelector(obj)
            })
            .ToList();
    }

and you would use it much like your current one, the only difference is I added another selector to set the Selected boolean property.

What about using something like this

IEnumerable<SelectListItem> data = Roles.Select(f => new SelectListItem { Value = f.RoleUID, Text = f.Name});

It works for me!

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