-2

I need Something like

var enumConstants =
        Enum.GetValues(enumType)
            .Cast<Enum>()
            .Select(x => ...);

as explained in this answer. But I get InvalidCastException.

Update:

Sorry, the problem was somewhere else. I had something like:

var enumConstants =
        Enum.GetValues(enumType)
            .Cast<Enum>()
            .Select(e => new SomeClass{Value = (int)Convert.ChangeType(e, e.GetTypeCode()), ...}).ToList();

and apparently Value = (int)Convert.ChangeType(e, e.GetTypeCode() caused the problem. Which I don't know why.

Yusif
  • 183
  • 2
  • 8

1 Answers1

2

If you have an enum as below:

    public enum yourEnum
    {
        A1,
        A2,
        A3,
        A4
    }

You can use the following code:

var enumValues =Enum.GetValues(typeof(yourEnum)).
         Cast<yourEnum>().Select(x => new { Value = (int)x, Name = x.ToString() });

Probably the problem with your code is .Cast<Enum>() which should be .Cast<yourEnum>().

Hossein Sabziani
  • 1
  • 2
  • 15
  • 20
  • 1
    +1. Although in my case casting to ```Enum``` is more favorable, because I have ```MyEnum``` as a generic type parameter, and unfortunately a type constraint of ```Enum``` is not possible. Anyways, this solution with some undesired changes made it work for me. Thanks. – Yusif Jan 29 '23 at 12:26