c# – How do I convert an enum between (string, list of flags, enum with flags)?

c# – How do I convert an enum between (string, list of flags, enum with flags)?

Update 2

there is a library that implements most of the functionality you would need from enums, with better performance
https://github.com/TylerBrinkley/Enums.NET


From Enum To String: [Enum Instance].ToString();

Example: using System.Windows.Input;

ModifierKeys mk = ModifierKeys.None | ModifierKeys.Alt | ModifierKeys.Shift | ModifierKeys.Control;
mk.Tostring();

returns:

Alt, Control, Shift
Note: None flag got removed


From string to Enum:

Enum.TryParse([(string) value],out [store variable]);
OR
Enum.Parse(typeof([Enum Type]), [(string) value], [(bool) should ignore character case ?]);

Example: using System.Windows.Input;

// Way 1:
ModifierKeys outenum;
bool successful = Enum.TryParse(None,Alt,Control,Shift, out outenum);

Console.WriteLine($Is Successful ? : {successful}, result : {outenum.ToString()});

Result: Is Successful ? : True, result : Alt, Control, Shift

OR

// Way 2:
ModifierKeys outenum = (ModifierKeys)Enum.Parse(typeof(ModifierKeys), None,Alt,Control,Shift, true);
Console.WriteLine(outenum.ToString());

Result: Alt, Control, Shift


From Enum Flags to List

Example:

        ModifierKeys mk = ModifierKeys.None | ModifierKeys.Alt | ModifierKeys.Shift | ModifierKeys.Control;
        List<ModifierKeys> mklist =
            mk
            .ToString() // Convert the enum to string
            .Split(new[] { , } , StringSplitOptions.RemoveEmptyEntries) // Converts the string to Enumerable of string
            .Select(//converts each element of the list to an enum, and makes an Enumerable out of the newly-converted items
                strenum =>
                {
                    ModifierKeys outenum;
                    Enum.TryParse(strenum , out outenum);
                    return outenum;
                })
            .ToList(); // Creates a List from the Enumerable

Result: {ModifierKeys.Alt , ModifierKeys.Shift , ModifierKeys.Control}


From List of enum flags to enum

Example:

 ModifierKeys[] mk = {ModifierKeys.None, ModifierKeys.Alt, ModifierKeys.Control, ModifierKeys.Shift};
 ModifierKeys mkc = mk.Aggregate((prev, next) => prev | next);
 Console.WriteLine(mkc.ToString());

Result: Alt, Control, Shift


From List of string to enum

Example:

    string[] mk = {None, Alt, Control, Shift};
    ModifierKeys mkc = mk.Select(x => {ModifierKeys outenum; Enum.TryParse(x, out outenum); return outenum;}).Aggregate((prev , next) => prev | next);
    Console.WriteLine(mkc.ToString());

Result: Alt, Control, Shift


General notes:

  • Using way 1 when converting from string to Enum is preferred, because if way 2 fails it throws an exception, but if way 1 fails it returns false
  • When separating enum flags while parsing enum string, use the , separator only
  • Having spaces between flags in enum string wont matter, so
    None , Alt,Control, Shift = None,Alt,Control,Shift

UPDATE 1 :

I wrote a simple Generic EnumConverter class that saves you time

public class EnumConverter<T> where T : struct, IConvertible, IFormattable
{
    private Type EnumType { get; set; }

    public Type UnderlyingType
    {
        get
        {
            return Enum.GetUnderlyingType(EnumType);
        }
    }
    public EnumConverter()
    {
        if (typeof(T).IsEnum)
            EnumType = typeof(T);
        else
            throw new ArgumentException(Provided type must be an enum);
    }
    public IEnumerable<T> ToFlagsList(T FromSingleEnum)
    {
        return FromSingleEnum.ToString()
        .Split(new[] { , } , StringSplitOptions.RemoveEmptyEntries)
        .Select(
            strenum =>
            {
                T outenum = default(T);
                Enum.TryParse(strenum , true , out outenum);
                return outenum;
            });
    }
    public IEnumerable<T> ToFlagsList(IEnumerable<string> FromStringEnumList)
    {
        return FromStringEnumList
        .Select(
            strenum =>
            {
                T outenum = default(T);
                Enum.TryParse(strenum , true , out outenum);
                return outenum;
            });
    }

    public T ToEnum(string FromString)
    {
        T outenum = default(T);
        Enum.TryParse(FromString , true , out outenum);
        return outenum;
    }
    public T ToEnum(IEnumerable<T> FromListOfEnums)
    {
        var provider = new NumberFormatInfo();
        var intlist = FromListOfEnums.Select(x => x.ToInt32(provider));
        var aggregatedint = intlist.Aggregate((prev , next) => prev | next);
        return (T)Enum.ToObject(EnumType , aggregatedint);
    }
    public T ToEnum(IEnumerable<string> FromListOfString)
    {
        var enumlist = FromListOfString.Select(x =>
        {
            T outenum = default(T);
            Enum.TryParse(x , true , out outenum);
            return outenum;
        });
        return ToEnum(enumlist);
    }

    public string ToString(T FromEnum)
    {
        return FromEnum.ToString();
    }
    public string ToString(IEnumerable<T> FromFlagsList)
    {
        return ToString(ToEnum(FromFlagsList));
    }

    public object ToUnderlyingType(T FromeEnum)
    {
        return Convert.ChangeType(FromeEnum , UnderlyingType);
    }
}

Usage :

 EnumConverter<ModifierKeys> conv = new EnumConverter<ModifierKeys>();
 //conv.ToEnum
 //conv.ToFlagsList
 //conv.ToString

c# – How do I convert an enum between (string, list of flags, enum with flags)?

Leave a Reply

Your email address will not be published. Required fields are marked *