Convert any IEnumerable to Select List

This little extension convert any type of IEnumerable to a Select List.

Here is the definition for the extension.

public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> items, Func<T, string> text, Func<T, string> value = null, Func<T, Boolean> selected = null)
        {
            return items.Select(p => new SelectListItem
            {
                Text = text.Invoke(p),
                Value = (value == null ? text.Invoke(p) : value.Invoke(p)),
                Selected = selected != null && selected.Invoke(p)
            });
        }

 

Here is how too call this extension.

					<div class="grid-9-12">                        
						@Html.DropDownListFor(x => x.AttributeModel.AttributeGroupId,
						Model.AttributeGroups.ToSelectList(y=>y.Name,y=>y.AttributeGroupId.ToString()),
						"Choose a attribute group...",
						new { @class = "chzn-select", style = "max-width: 350px;",tabindex="1" }) 
					</div>

Comments are closed.