Most efficient way to parse a flagged enum to a list

前端 未结 6 1405
猫巷女王i
猫巷女王i 2021-01-01 09:06

I have a flagged enum and need to retrieve the names of all values set on it.

I am currently taking advantage of the enum\'s ToString() method which returns the eleme

6条回答
  •  滥情空心
    2021-01-01 09:38

    If you genuinely just want the strings, can't get much simpler than:

    string[] flags = role.ToString().Split(',');

    This is simpler than using LINQ and is still just a single line of code. Or if you want a list instead of an array as in the sample in the question you can convert the array into a list:

    List flags = new List(role.ToString().Split(','));

    In my case I needed a generic solution and came up with this:

    value.ToString().Split(',').Select(flag => (T)Enum.Parse(typeof(T), flag)).ToList();

提交回复
热议问题