Home > Blockchain >  Get int value from enum with where clause
Get int value from enum with where clause

Time:10-22

I have this enum :

public enum MyEnum
{
    A = 0,
    B = 1,
    C = 2,
    D = 3,
    E = 4
}

I have a List<string> {"A", "C", "E"}

I'd like make a query on MyEnum to get back the int values as a List<int> Here the result should be 0,2,4

Same question but when I have a List<int> {0, 2, 4} I'd like get back a List<string> with A,C,E

Do you have an idea how do this in .NET 4.7 ?

Thanks,

CodePudding user response:

If you are sure they exist you can parse them and use List.ConvertAll:

List<string> list = new() { "A", "C", "E" };
List<int> result = list.ConvertAll(s => (int)(MyEnum)Enum.Parse(typeof(MyEnum), s));

to get the strings back, so the opposite way:

list = result.ConvertAll(i => ((MyEnum)i).ToString());

CodePudding user response:

From names to values:

using System.Linq;

...

List<string> names = new List<string>() { "A", "C", "E" };

// If there's no guarantee that name is a correct enum name
// use TryParse instead of Parse
var values = names
  .Select(name => Convert.ToInt32(Enum.Parse(typeof(MyEnum), name)))
  .ToList();

From values to names:

using System.Linq;

...

List<int> values = new List<int>() { 0, 2, 4 };

var names = values
  .Select(value => ((MyEnum)value).ToString())
  .ToList();

Please, fiddle

  • Related