Mediator
Mediator

Reputation: 15378

How set in value type int?

I need set value int. how do this?

    var list = from Enum e in Enum.GetValues(enumValue.GetType())
           select new SelectListItem
           {
               Selected = e.Equals(enumValue),
               Text = e.ToDescription(),
               Value = e.ToString()// need int
           };

if I set Value = ((int)e).ToString()

I get error:

Cannot convert type 'System.Enum' to 'int'

Upvotes: 0

Views: 190

Answers (6)

Tony The Lion
Tony The Lion

Reputation: 63190

AFAIK in C#, Enums can be convert to int:

 Value = ((int)e).ToString()

That is as long as the underlying type is an int or castable to an int.

Upvotes: 2

Oded
Oded

Reputation: 498914

Cast to an int and get a string from it:

Value = ((int)e).ToString()

All enumerations are based on integer types, so a cast is the simplest solution (though if the enum is based on a long, you may get an overflow).

Additionally, the type returned from Enum.GetValues is the values of the enumeration - your LINQ should be:

from e in Enum.GetValues(enumValue.GetType())

As e will not be of type Enum.

Upvotes: 2

Jay Jose
Jay Jose

Reputation: 31

you can convert enum directly by casting it to int type.

Upvotes: 0

eridanix
eridanix

Reputation: 828

    var list = from Enum e in Enum.GetValues(enumValue.GetType())
       select new SelectListItem
       {
           Selected = e.Equals(enumValue),
           Text = e.ToDescription(),
           Value = (int) e
       };

Upvotes: 0

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28970

You can try with

(int)YourEnum.enumValue; 

or

(int)e

Upvotes: 0

John Woo
John Woo

Reputation: 263693

Value = Convert.ToInt32(e.ToString())

Upvotes: 1

Related Questions