本文翻译自:How do I convert an enum to a list in C#? [duplicate]
This question already has an answer here: 这个问题在这里已有答案:
- How do I enumerate an enum in C#? 如何在C#中枚举枚举? 26 answers 26个答案
Is there a way to convert an enum
to a list that contains all the enum's options? 有没有办法将enum
转换为包含所有枚举选项的列表?
#1楼
参考:https://stackoom.com/question/4tgP/如何将枚举转换为C-中的列表-重复
#2楼
You could use the following generic method: 您可以使用以下通用方法:
public static List<T> GetItemsList<T>(this int enums) where T : struct, IConvertible
{
if (!typeof (T).IsEnum)
{
throw new Exception("Type given must be an Enum");
}
return (from int item in Enum.GetValues(typeof (T))
where (enums & item) == item
select (T) Enum.Parse(typeof (T), item.ToString(new CultureInfo("en")))).ToList();
}
#3楼
/// <summary>
/// Method return a read-only collection of the names of the constants in specified enum
/// </summary>
/// <returns></returns>
public static ReadOnlyCollection<string> GetNames()
{
return Enum.GetNames(typeof(T)).Cast<string>().ToList().AsReadOnly();
}
where T is a type of Enumeration; 其中T是一种枚举; Add this: 添加这个:
using System.Collections.ObjectModel;
#4楼
If you want Enum int as key and name as value, good if you storing the number to database and it is from Enum! 如果你想将Enum int作为键并将name命名为value,那么如果你将数字存储到数据库并且它来自Enum,那就太好了!
void Main()
{
ICollection<EnumValueDto> list = EnumValueDto.ConvertEnumToList<SearchDataType>();
foreach (var element in list)
{
Console.WriteLine(string.Format("Key: {0}; Value: {1}", element.Key, element.Value));
}
/* OUTPUT:
Key: 1; Value: Boolean
Key: 2; Value: DateTime
Key: 3; Value: Numeric
*/
}
public class EnumValueDto
{
public int Key { get; set; }
public string Value { get; set; }
public static ICollection<EnumValueDto> ConvertEnumToList<T>() where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
throw new Exception("Type given T must be an Enum");
}
var result = Enum.GetValues(typeof(T))
.Cast<T>()
.Select(x => new EnumValueDto { Key = Convert.ToInt32(x),
Value = x.ToString(new CultureInfo("en")) })
.ToList()
.AsReadOnly();
return result;
}
}
public enum SearchDataType
{
Boolean = 1,
DateTime,
Numeric
}
#5楼
This will return an IEnumerable<SomeEnum>
of all the values of an Enum. 这将返回Enum的所有值的IEnumerable<SomeEnum>
。
Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>();
If you want that to be a List<SomeEnum>
, just add .ToList()
after .Cast<SomeEnum>()
. 如果你想要它是List<SomeEnum>
,只需在.Cast<SomeEnum>()
之后添加.ToList()
.Cast<SomeEnum>()
。
To use the Cast function on an Array you need to have the System.Linq
in your using section. 要在Array上使用Cast函数,您需要在using部分中使用System.Linq
。
#6楼
very simple answer 非常简单的答案
Here is a property I use in one of my applications 这是我在我的一个应用程序中使用的属性
public List<string> OperationModes
{
get
{
return Enum.GetNames(typeof(SomeENUM)).ToList();
}
}