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

时间:2013-06-12 16:34:19

标签: c#

我刚刚更改了代码,现在它将一些数据存储在枚举中,而不是存储在SQL Server表中。

这是枚举:

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

我正在运行以下代码:

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

如何更改此设置,以便不是从内容服务中获取数据,而只是查询枚举内容类型的数据?

2 个答案:

答案 0 :(得分:4)

我认为你想要的是这个

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

答案 1 :(得分:3)

pswg可能是对的,但我想你想要something like this

以下代码更直接针对您的问题:

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

您只需转换为int即可获取整数ID,并使用其ToString获取其名称(此处可能隐含也可能不隐含)