Gibt es eine Möglichkeit zur Konvertierung eines enum
zu einer Liste, die alle Optionen der Aufzählung enthält?
Diese Frage hat bereits Antworten:
- Wie man eine Aufzählung durchführt (33 Antworten )
Antworten
Zu viele Anzeigen?
Mohammad Eftekhari
Punkte
51
private List<SimpleLogType> GetLogType()
{
List<SimpleLogType> logList = new List<SimpleLogType>();
SimpleLogType internalLogType;
foreach (var logtype in Enum.GetValues(typeof(Log)))
{
internalLogType = new SimpleLogType();
internalLogType.Id = (int) (Log) Enum.Parse(typeof (Log), logtype.ToString(), true);
internalLogType.Name = (Log)Enum.Parse(typeof(Log), logtype.ToString(), true);
logList.Add(internalLogType);
}
return logList;
}
in top Code , Log ist ein Enum und SimpleLogType ist eine Struktur für Logs .
public enum Log
{
None = 0,
Info = 1,
Warning = 8,
Error = 3
}
frigate
Punkte
21
/// <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();
}
wobei T ist ein Typ einer Aufzählung; Dies hinzufügen:
using System.Collections.ObjectModel;
xajler
Punkte
31
Wenn Sie Enum int als Schlüssel und Name als Wert wollen, gut, wenn Sie die Nummer in der Datenbank speichern und es ist von 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
}
Vitall
Punkte
1131
Sie können die folgende generische Methode verwenden:
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();
}
- See previous answers
- Weitere Antworten anzeigen