Ccna final exam - java, php, javascript, ios, cshap all in one. This is a collaboratively edited question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
Monday, June 4, 2012
Can You Loop Through All Enum Values? c#
public enum Foos
{
A,
B,
C
}
Is there a way to loop through the possible values of Foo?
/// <summary> /// Returns a generic list of all values for an enum. /// Taken from http://devlicio.us/blogs/joe_niland/archive/2006/10/10/Generic-Enum-to-List_3C00_T_3E00_-converter.aspx /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static IList<T> EnumToList<T>() { Type enumType = typeof(T);
// Can't use type constraints on value types, so have to do check like this if (enumType.BaseType != typeof(Enum)) throw new ArgumentException("T must be of type System.Enum");
Array enumValArray = Enum.GetValues(enumType);
List<T> enumValList = new List<T>(enumValArray.Length);
foreach (int val in enumValArray) { enumValList.Add((T)Enum.Parse(enumType, val.ToString())); }
Yes you can use the GetValues method
ReplyDeletevar values = Enum.GetValues(typeof(Foos));
Or the typed version
var values = Enum.GetValues(typeof(Foos)).Cast<Foos>();
I long ago added a helper function to my private library for just such an occasion
public static class EnumUtil {
public static IEnumerable<T> GetValues<T>() {
return Enum.GetValues(typeof(T)).Cast<T>();
}
}
Usage:
var values = EnumUtil.GetValues<Foos>();
foreach(Foos foo in Enum.GetValues(typeof(Foos)))
ReplyDeleteforeach (EMyEnum val in Enum.GetValues(typeof(EMyEnum)))
ReplyDelete{
Console.WriteLine(val);
}
Credit to Jon Skeet here: http://bytes.com/groups/net-c/266447-how-loop-each-items-enum
foreach (Foos foo in Enum.GetValues(typeof(Foos)))
ReplyDelete{
...
}
/// <summary>
ReplyDelete/// Returns a generic list of all values for an enum.
/// Taken from http://devlicio.us/blogs/joe_niland/archive/2006/10/10/Generic-Enum-to-List_3C00_T_3E00_-converter.aspx
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static IList<T> EnumToList<T>()
{
Type enumType = typeof(T);
// Can't use type constraints on value types, so have to do check like this
if (enumType.BaseType != typeof(Enum))
throw new ArgumentException("T must be of type System.Enum");
Array enumValArray = Enum.GetValues(enumType);
List<T> enumValList = new List<T>(enumValArray.Length);
foreach (int val in enumValArray)
{
enumValList.Add((T)Enum.Parse(enumType, val.ToString()));
}
return enumValList;
}
static void Main(string[] args)
ReplyDelete{
foreach (int value in Enum.GetValues(typeof(DaysOfWeek)))
{
Console.WriteLine(((DaysOfWeek)value).ToString());
}
foreach (string value in Enum.GetNames(typeof(DaysOfWeek)))
{
Console.WriteLine(value);
}
Console.ReadLine();
}
public enum DaysOfWeek
{
monday,
tuesday,
wednesday
}
}
Yes. Use "GetValues" method in System.Enum class.
ReplyDeleteEnum.GetValues(typeof(Foos))
ReplyDelete