You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
iot/projects/Infrastructure/Extensions/EnumExtensions.cs

58 lines
1.7 KiB

using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace Infrastructure.Extensions
{
public static class EnumExtensions
{
public static string GetName(this Enum value)
{
if (value is null)
{
throw new ArgumentNullException(nameof(value));
}
var type = value.GetType();
return Enum.GetName(type, value);
}
public static int GetValue(this Enum value)
{
if (value is null)
{
throw new ArgumentNullException(nameof(value));
}
return (int)Enum.ToObject(value.GetType(), value);
}
public static string GetDisplayName(this Enum value)
{
if (value is null)
{
throw new ArgumentNullException(nameof(value));
}
var type = value.GetType();
var name = Enum.GetName(type, value);
if (name == null)
{
return null;
}
var field = type.GetField(name);
var attribute = Attribute.GetCustomAttribute(field, typeof(DisplayAttribute)) as DisplayAttribute;
return attribute?.Name ?? name;
}
public static SelectList GetSelectList(this Enum value)
{
if (value is null)
{
throw new ArgumentNullException(nameof(value));
}
var values = from Enum e in Enum.GetValues(value.GetType())
select new { Id = e, Name = e.ToString() };
return new SelectList(values, "Id", "Name", value);
}
}
}