// --------------------------------------------------------------------------------------------------------------------
//
// This file is part of the HandBrake source code - It may be used under the terms of the GNU General Public License.
//
//
// Enum Helpers
//
// --------------------------------------------------------------------------------------------------------------------
namespace HandBrake.ApplicationServices.Utilities
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
///
/// Enum Helpers
///
///
/// The Type Parameter
///
public class EnumHelper
{
///
/// Get the description of an Enum
///
///
/// The value.
///
///
/// The Description string
///
public static string GetDescription(T value)
{
FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fieldInfo.GetCustomAttributes(
typeof(DescriptionAttribute), false);
return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
}
///
/// Get the Display Value of the Enum Model
///
/// An Enum with Display Attributes
/// A string name
public static string GetDisplay(T value)
{
FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
DisplayAttribute[] attributes = (DisplayAttribute[])fieldInfo.GetCustomAttributes(typeof(DisplayAttribute), false);
return (attributes.Length > 0) ? attributes[0].Name : value.ToString();
}
///
/// Get the Enumeration for a given Enum Description
///
/// The String description
/// The Enum Value
public static T GetValue(string description)
{
foreach (T val in Enum.GetValues(typeof(T)))
{
string currDescription = GetDescription(val);
string currDisplay = GetDisplay(val);
if (currDescription == description || currDisplay == description)
{
return val;
}
}
throw new ArgumentOutOfRangeException("The Description for the enum was not recognized.");
}
///
/// Return a list of all the enum values.
///
///
/// An Enum Oject List
///
public static IEnumerable GetEnumList()
{
return Enum.GetValues(typeof(T)).Cast().ToList();
}
///
/// Get a list of string names for each enum value.
///
///
/// The enum type.
///
///
/// The type of the enum
///
///
/// A collection of strings that represent all the enum values
///
public static IEnumerable GetEnumDisplayValues(Type enumType)
{
var strings = new Collection();
foreach (T e in Enum.GetValues(enumType))
strings.Add(GetDisplay(e));
return strings;
}
///
/// Get a list of string names for each enum value passed in.
///
///
/// The items.
///
///
/// The type of the enum
///
///
/// A collection of strings that represent all the enum values
///
public static IEnumerable GetEnumDisplayValuesSubset(IEnumerable items)
{
return items.Select(GetDisplay).ToList();
}
}
}