In my query string, I have an age variable ?age=New_Born
.
Is there a way I can check if this string value New_Born
is in my Enum list
I know this is an old thread, but here's a slightly different approach using attributes on the Enumerates and then a helper class to find the enumerate that matches.
This way you could have multiple mappings on a single enumerate.
public enum Age
{
[Metadata("Value", "New_Born")]
[Metadata("Value", "NewBorn")]
New_Born = 1,
[Metadata("Value", "Toddler")]
Toddler = 2,
[Metadata("Value", "Preschool")]
Preschool = 4,
[Metadata("Value", "Kindergarten")]
Kindergarten = 8
}
With my helper class like this
public static class MetadataHelper
{
public static string GetFirstValueFromMetaDataAttribute(this T value, string metaDataDescription)
{
return GetValueFromMetaDataAttribute(value, metaDataDescription).FirstOrDefault();
}
private static IEnumerable GetValueFromMetaDataAttribute(T value, string metaDataDescription)
{
var attribs =
value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof (MetadataAttribute), true);
return attribs.Any()
? (from p in (MetadataAttribute[]) attribs
where p.Description.ToLower() == metaDataDescription.ToLower()
select p.MetaData).ToList()
: new List();
}
public static List GetEnumeratesByMetaData(string metadataDescription, string value)
{
return
typeof (T).GetEnumValues().Cast().Where(
enumerate =>
GetValueFromMetaDataAttribute(enumerate, metadataDescription).Any(
p => p.ToLower() == value.ToLower())).ToList();
}
public static List GetNotEnumeratesByMetaData(string metadataDescription, string value)
{
return
typeof (T).GetEnumValues().Cast().Where(
enumerate =>
GetValueFromMetaDataAttribute(enumerate, metadataDescription).All(
p => p.ToLower() != value.ToLower())).ToList();
}
}
you can then do something like
var enumerates = MetadataHelper.GetEnumeratesByMetaData("Value", "New_Born");
And for completeness here is the attribute:
[AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = true)]
public class MetadataAttribute : Attribute
{
public MetadataAttribute(string description, string metaData = "")
{
Description = description;
MetaData = metaData;
}
public string Description { get; set; }
public string MetaData { get; set; }
}