5

I have this enum:

[Flags]
public enum Countries
{
    None    = 0,
    USA     = 1,
    Mexico  = 2,
    Canada  = 4,
    Brazil  = 8,
    Chile   = 16
}

I receive in input strings like these:

string selectedCountries = "Usa, Brazil, Chile";

how to convert it (in C#) back to:

var myCountries = Countries.Usa | Countries.Brazil | Countries.Chile;
Paul_T
  • 55
  • 5

3 Answers3

9

Use Enum.Parse.

e.g. Countries c = (Countries)Enum.Parse(typeof(Countries), "Usa, Brazil...");

tyranid
  • 13,028
  • 1
  • 32
  • 34
  • I agree it should Enum.Parse but don't think you can pass in the whole string directly into Enum.Parse. – dragonfly02 Oct 29 '16 at 11:36
  • Yes you can I just tested it. You are actually converting that string into a number and then casting it to enum. Thanks Tyranid – Paul_T Oct 29 '16 at 11:41
  • @Paul_T are you saing you can pass the string `Usa, Brazil` directly into `Enum.Parse` and it works? – dragonfly02 Oct 29 '16 at 11:43
  • That's correct stt106: if you pass the string "Usa, Brazil, Chile" to the Enum.parse it will work. After this call Countries c = (Countries)Enum.Parse(typeof(Countries), "Usa, Brazil..."); c stores Countries.Usa | Countries.Brazil | Countries.Chile – Paul_T Oct 29 '16 at 11:53
  • If you want to avoid possible exception use Enum.TryParse("Usa, Brazil", out Countries c) – Pavel Popov Apr 07 '22 at 12:06
3

This seems to work for me assuming your country string is separated by a comma:

private static Countries ConvertToCountryEnum(string country)
        {
            return country.Split(',').Aggregate(Countries.None, (seed, c) => (Countries)Enum.Parse(typeof(Countries), c, true) | seed);
        }
dragonfly02
  • 3,403
  • 32
  • 55
0

Actually I realized that it is easier than what i thought. All I need to do is convert that string into an int, in my case, or a long in general, and cast it to Countries. It will convert that number into the expected format. In other words:

(Countries) 25 = Countries.Usa | Countries.Brazil | Countries.Chile;
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Paul_T
  • 55
  • 5