从字典中获取值到modelitem属性

时间:2016-07-04 07:56:13

标签: c# dictionary

我是C#中字典数据类型的新手。我得到了这个模型项目:

  public Dictionary<int, string> language { get; set; }
  public string languageChoice { get; set; }

然后在我的控制器中我得到了这个:

  [Route("{id}/settings")]
  [HttpGet]
  public async Task<HttpResponseMessage> GetProjectSettings(Guid id)
  {
     var projectSettings = new ProjectSettings
     {
        Id = id,       
        language = new Dictionary<int, string>() {
                           {1,"English"},
                           {2,"Spanish"}},
        languageChoice = //get language by ID        

     };

     if (projectSettings != null)
     {
        return Request.CreateResponse<ProjectSettings>(HttpStatusCode.OK, projectSettings);

     }
     else
     {
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Project not found");
     }
  }

我想给json对象提供整数而不是语言的String。我怎么能这样做?

亲切的问候

1 个答案:

答案 0 :(得分:0)

如果您不想更改现有的Dictionary<int, string>,则可以从中创建新的Dictionary<int, int>

var alteredDictionary = languages.ToDictionary(x => x.Key, x => x.Key);

然后做

 var projectSettings = new ProjectSettings
 {
    Id = id,       
    language = new Dictionary<int, string>() {
                       {1,"English"},
                       {2,"Spanish"}},
    languageChoice = alteredDictionary[1]// optional .ToString() if you want string        
 };

1是您想要的语言ID。