Select List Of Enum Values - CSharp System

CSharp examples for System:Enum

Description

Select List Of Enum Values

Demo Code


using System.Web.Mvc;
using System.Linq;
using System.ComponentModel;
using System.Collections.Generic;
using System;//from   w w  w . java 2 s  . co  m

public class Main{
        public static List<SelectListItem> SelectListOfEnumValues<T>(bool hasNullItem)
        {
            if (!typeof (T).IsEnum) 
                return new List<SelectListItem>();

            var result = new List<SelectListItem>();
            if (hasNullItem)
            {
                result.Add(new SelectListItem { Text = "", Value = null });
            }
            result.AddRange(
                (from object type in Enum.GetValues(typeof(T))
                    select new SelectListItem
                    {
                        Text = type.ToString(),
                        Value = type.ToString()
                    }));
            return result.ToList();
        }
}

Related Tutorials