选择基于enum参数而不用swich case?

时间:2018-06-05 08:07:08

标签: c# asp.net-mvc linq enums

考虑我们有这个表,因为你可以看到我们保持文章状态的字符串字段

ArticleState可以是New,Draft或Published

USE [test]
GO

CREATE TABLE [dbo].[Article](
    [id] [int] NOT NULL PRIMARY KEY CLUSTERED,
    [ArticleState] [nvarchar](100) NOT NULL,
    [Title] [nvarchar](255) NOT NULL,
    [Content] [nvarchar](max) NOT NULL
)

GO

INSERT INTO Article VALUES (1,'New','title1','this is a test');
INSERT INTO Article VALUES (2,'Draft','title2','this is a test');
INSERT INTO Article VALUES (3,'New','title3','this is a test');
INSERT INTO Article VALUES (4,'Published','title4','this is a test');
GO

我们有这个枚举

public enum ArticleStateEnum
    {
        [EnumDescription("Draft Articles")]
        Draft = 10,

        [EnumDescription("New Articles")]
        New = 20,

        [EnumDescription("Published Articles ")]
        Published = 30,
    }

我们如何根据ArticleState选择文章? 我的意思是我可以写什么而不是什么?

    // GET: Articles
    public ActionResult Index()
    {
      var result=  GetArticlesByState(ArticleStateEnum.Draft);
        return View(result);
    }
    public void GetArticlesByState(ArticleStateEnum nse)
    {

        var articleList = db.Articles.Where(x => x.ArticleState ==  ??????????????????????????????);
    }

2 个答案:

答案 0 :(得分:3)

假设您无法更改数据库表示,您只需使用ToString调用获取字符串值:

public void GetArticlesByState(ArticleStateEnum nse)
{
    string stateText = nse.ToString();
    var articleList = db.Articles.Where(x => x.ArticleState == stateText);
    ...
}

答案 1 :(得分:1)

我会使用Enum.GetName(typeof(ArticleStateEnum), nse)

要么:

public void GetArticlesByState(ArticleStateEnum nse)
{
    var articleList = db.Articles
         .Where(x => x.ArticleState == Enum.GetName(typeof(ArticleStateEnum), nse));
}

或者喜欢:

public void GetArticlesByState(ArticleStateEnum nse)
{
    string state = Enum.GetName(typeof(ArticleStateEnum), nse);
    var articleList = db.Articles.Where(x => x.ArticleState == state);
}

请注意,此解决方案即使使用int值也能正常工作(只要该值与枚举值匹配):

public void GetArticlesByState(int nse)
{
    string state = Enum.GetName(typeof(ArticleStateEnum), nse);
    var articleList = db.Articles.Where(x => x.ArticleState == state);
}