Alan2
Alan2

Reputation: 24572

How can I select a number and value from an enum in C#?

I have just changed my code so that now it stores some data in an enum instead of in a SQL Server table.

Here's the enum:

public enum ContentTypes : int
{
    Article = 0,
    Menu = 1,
    ContentBlock = 3
}

I was running the following code:

        var contentTypes =
          (
              from contentType in this._contentTypeService.GetContentTypes()
              select new
              {
                  id = contentType.ContentTypeId,
                  name = contentType.Name
              }
          );

How can I change this so that instead of taking the data from the content service it just queries the enum to data for contentTypes?

Upvotes: 2

Views: 106

Answers (2)

Justin Pihony
Justin Pihony

Reputation: 67115

pswg might be right, but I am thinking you want something like this?

Here is code more direct to your question:

select new
{
    id = (int)contentType,
    name = contentType.ToString()
}

You can get the integer id simply by casting to an int and get the name of it by using its ToString (which may or may not be implicit here)

Upvotes: 3

p.s.w.g
p.s.w.g

Reputation: 149040

I think what you want is this

var contentTypes =
    from value in Enum.GetValues(typeof(ContentTypes)).Cast<int>()
    select new
    {
        id = value,
        name = Enum.GetName(typeof(ContentTypes), value)
    };

Upvotes: 4

Related Questions