In one of scenario i want to return Enum to List with to list datasource, for that here i have drafted method which converts enum type to Generic List
132 /// <summary>
133 /// Converts a enum to a list
134 /// </summary>
135 /// <typeparam name=”T”>string name of type of Enum</typeparam>
136 /// <returns>An enumerable list of Enum Type “T”</returns>
137 /// <remarks>
138 /// Usage:
139 /// var list = StringComparison.CurrentCulture.EnumToList();
140 /// </remarks>
141 public static IEnumerable<T> EnumToList<T>(this T enumName) where T : struct
142 {
143 Type enumType = enumName.GetType();
144 // Can’t use generic type constraints on value types,
145 // so have to do check like this
146 if (enumType.BaseType != typeof (Enum))
147 throw new ArgumentException(enumType + ” is not an Enum.”, “T”, null);
148 var enumValArray = Enum.GetValues(enumType);
149 var enumValList = new List<T>(enumValArray.Length);
150 foreach (int val in enumValArray)
151 {
152 enumValList.Add((T) Enum.Parse(enumType, val.ToString()));
153 }
154 return enumValList;
155 }
156 }
here how you can access it.
128 var list = StringComparison.CurrentCulture.EnumToList();
129 foreach (var enumValue in list)
130 {
131 …
132 }
Happy coding.