简体   繁体   English

如何从C#枚举中选择数字和值?

[英]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. 我刚刚更改了代码,现在它将一些数据存储在枚举而不是SQL Server表中。

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? 我该如何更改它,以便代替从内容服务中获取数据,而只查询枚举到contentTypes的数据?

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)
    };

pswg might be right, but I am thinking you want something like this ? pswg可能是对的,但我想你想要这样的东西

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) 您可以简单地通过转换为int来获取整数id并使用其ToString来获取其名称(此处可能隐含或不隐含)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM