web-dev-qa-db-fra.com

Comment vérifier si la valeur de chaîne est dans la liste Enum?

Dans ma chaîne de requête, j'ai une variable d'âge ?age=New_Born.

Est-il possible de vérifier si cette valeur de chaîne New_Born est dans ma liste d'énumération

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

Je pourrais utiliser if si pour le moment, mais si ma liste Enum devenait plus grande. Je veux trouver un meilleur moyen de le faire. Je pense à utiliser Linq, mais je ne sais pas trop comment le faire.

80
qinking126

Vous pouvez utiliser:

 Enum.IsDefined(typeof(Age), youragevariable)
135
AaronS

Vous pouvez utiliser la méthode Enum.TryParse:

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

Vous pouvez utiliser la méthode TryParse qui renvoie true si elle réussit:

Age age;

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

Je sais que c'est un vieux fil, mais voici une approche légèrement différente qui utilise les attributs de la classe Enumerates, puis une classe d'assistance, pour trouver l'énumération correspondante.

De cette façon, vous pouvez avoir plusieurs mappages sur une seule énumération.

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
}

Avec mon cours d'aide comme ça

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();
    }

}

vous pouvez alors faire quelque chose comme

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

Et pour être complet voici l'attribut:

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

J'ai une méthode d'extension pratique qui utilise TryParse, car IsDefined est sensible à la casse.

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

Pour analyser l'âge:

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

Pour voir si c'est défini:

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

Selon l'utilisation envisagée de Age enum, flags peut ne pas convenir. Comme vous le savez probablement, [Flags] indique que vous souhaitez autoriser plusieurs valeurs (comme dans un masque de bits). IsDefined retournera false pour Age.Toddler | Age.Preschool parce qu'il a plusieurs valeurs.

0
agent-j

Vous devriez utiliser Enum.TryParse pour atteindre votre objectif

Ceci est un exemple:

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