是否有一种方法将枚举转换为包含所有枚举选项的列表?
当前回答
更简单的方法:
Enum.GetValues(typeof(SomeEnum))
.Cast<SomeEnum>()
.Select(v => v.ToString())
.ToList();
其他回答
这将返回一个枚举的所有值的IEnumerable<SomeEnum>。
Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>();
如果你希望它是一个List<SomeEnum>,只需在. cast <SomeEnum>()之后添加. tolist()。
要在数组上使用Cast函数,您需要拥有System。Linq在你的使用部分。
非常简单的答案
下面是我在一个应用程序中使用的属性
public List<string> OperationModes
{
get
{
return Enum.GetNames(typeof(SomeENUM)).ToList();
}
}
/// <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();
}
其中T是枚举类型; 添加:
using System.Collections.ObjectModel;
public class NameValue
{
public string Name { get; set; }
public object Value { get; set; }
}
public class NameValue
{
public string Name { get; set; }
public object Value { get; set; }
}
public static List<NameValue> EnumToList<T>()
{
var array = (T[])(Enum.GetValues(typeof(T)).Cast<T>());
var array2 = Enum.GetNames(typeof(T)).ToArray<string>();
List<NameValue> lst = null;
for (int i = 0; i < array.Length; i++)
{
if (lst == null)
lst = new List<NameValue>();
string name = array2[i];
T value = array[i];
lst.Add(new NameValue { Name = name, Value = value });
}
return lst;
}
转换枚举到一个列表更多的信息可在这里。
更简单的方法:
Enum.GetValues(typeof(SomeEnum))
.Cast<SomeEnum>()
.Select(v => v.ToString())
.ToList();
推荐文章
- HTTP POST返回错误:417“期望失败。”
- 如何在。net中创建和使用资源
- 为什么Path。以Path.DirectorySeparatorChar开头的文件名合并不正确?
- 如何在c#中获得正确的时间戳
- Linq选择列表中存在的对象(A,B,C)
- c# .NET中的App.config是什么?如何使用它?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 我如何提高ASP。NET MVC应用程序性能?
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new
- 无法解析类型为“Microsoft.AspNetCore.Http.IHttpContextAccessor”的服务