如何检查字符串值是否在枚举列表中?

时间:2012-05-29 17:45:04

标签: c# c#-4.0 c#-3.0

在我的查询字符串中,我有一个年龄变量?age=New_Born

有没有办法可以检查此字符串值New_Born是否在我的枚举列表中

[Flags]
public enum Age
{
    New_Born = 1,
    Toddler = 2,
    Preschool = 4,
    Kindergarten = 8
}

我现在可以使用if语句,但是如果我的枚举列表变大了。我想找到一个更好的方法来做到这一点。我正在考虑使用Linq,只是不知道该怎么做。

7 个答案:

答案 0 :(得分:125)

您可以使用:

 Enum.IsDefined(typeof(Age), youragevariable)

答案 1 :(得分:33)

您可以使用Enum.TryParse方法:

Age age;
if (Enum.TryParse<Age>("New_Born", out age))
{
    // You now have the value in age 
}

答案 2 :(得分:7)

如果成功,您可以使用返回true的TryParse方法:

Age age;

if(Enum.TryParse<Age>("myString", out age))
{
   //Here you can use age
}

答案 3 :(得分:1)

我知道这是一个旧线程,但是这里有一个稍微不同的方法,使用Enumerates上的属性,然后是一个帮助器类来查找匹配的枚举。

这样,您就可以在单个枚举上进行多次映射。

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
}

我的助手类就像这样

public static class MetadataHelper
{
    public static string GetFirstValueFromMetaDataAttribute<T>(this T value, string metaDataDescription)
    {
        return GetValueFromMetaDataAttribute(value, metaDataDescription).FirstOrDefault();
    }

    private static IEnumerable<string> GetValueFromMetaDataAttribute<T>(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<string>();
    }

    public static List<T> GetEnumeratesByMetaData<T>(string metadataDescription, string value)
    {
        return
            typeof (T).GetEnumValues().Cast<T>().Where(
                enumerate =>
                    GetValueFromMetaDataAttribute(enumerate, metadataDescription).Any(
                        p => p.ToLower() == value.ToLower())).ToList();
    }

    public static List<T> GetNotEnumeratesByMetaData<T>(string metadataDescription, string value)
    {
        return
            typeof (T).GetEnumValues().Cast<T>().Where(
                enumerate =>
                    GetValueFromMetaDataAttribute(enumerate, metadataDescription).All(
                        p => p.ToLower() != value.ToLower())).ToList();
    }

}
然后,您可以执行类似

的操作
var enumerates = MetadataHelper.GetEnumeratesByMetaData<Age>("Value", "New_Born");

为了完整性,这里是属性:

 [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; }
}

答案 4 :(得分:1)

我有一个使用TryParse的方便的扩展方法,因为IsDefined是区分大小写的。

public static bool IsParsable<T>(this string value) where T : struct
{
    return Enum.TryParse<T>(value, true, out _);
}

答案 5 :(得分:0)

解析年龄:

Age age;
if (Enum.TryParse(typeof(Age), "New_Born", out age))
  MessageBox.Show("Defined");  // Defined for "New_Born, 1, 4 , 8, 12"

查看是否已定义:

if (Enum.IsDefined(typeof(Age), "New_Born"))
   MessageBox.Show("Defined");

根据您计划使用Age枚举的方式,标记可能不正确。您可能知道,[Flags]表示您希望允许多个值(如位掩码中)。 IsDefined会为Age.Toddler | Age.Preschool返回false,因为它有多个值。

答案 6 :(得分:0)

您应该使用Enum.TryParse来实现目标

这是一个例子:

[Flags]
private enum TestEnum
{
    Value1 = 1,
    Value2 = 2
}

static void Main(string[] args)
{
    var enumName = "Value1";
    TestEnum enumValue;

    if (!TestEnum.TryParse(enumName, out enumValue))
    {
        throw new Exception("Wrong enum value");
    }

    // enumValue contains parsed value
}
相关问题