简体   繁体   中英

How to convert from a string to a Flags enum format in C#

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;

Use Enum.Parse .

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

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM