开发者

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

开发者 https://www.devze.com 2023-04-08 19:42 出处:网络
I need a way to create an extension method off of an IEnumerable that will allow me to return a list of SelectListItem\'s.

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.

IMPORTANT I want this to be generic so I can create it with any two properties off of an object, not just an o开发者_C百科bject of type 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!

0

精彩评论

暂无评论...
验证码 换一张
取 消