将表转换为IEnumerable <selectlistitem> </selectlistitem>

时间:2014-10-09 15:27:17

标签: c# dictionary collections asp.net-mvc-5

我需要填充数据库表中的Drop down键和值。我正在做的是

        Dictionary<int, string> states = resultSet.Tables[0].AsEnumerable()
                             .ToDictionary(row => row.Field<int>(0),
                                                       row => row.Field<string>(1)); 
        //Add the list item 
        states.Add(0, "Select State");
        //Sort the dictionary to set the "0" item at the top
        var sortedStates = (from entry in states orderby entry.Key ascending select entry)
                    .ToDictionary(pair => pair.Key, pair => pair.Value);

        //Form the SelectListItem
        model.State = from s in sortedStates
                      select new SelectListItem()
                      {
                          Text = s.Value,
                          Value = s.Key.ToString(CultureInfo.InvariantCulture)
                      };

我得到了正确的输出,但我觉得它更精细。有没有最好的方法来填充MVC中的下拉列表。

先谢谢

2 个答案:

答案 0 :(得分:1)

如果您想通过密钥订购,为什么要使用Dictionary?您可以使用ListInsert

List<SelectListItem> allItems = resultSet.Tables[0].AsEnumerable()
    .OrderBy(r => r.Field<int>(0))
    .Select(r => new SelectListItem { Text = r.Field<string>(1), Value = r.Field<int>(0).ToString() })
    .ToList();

SelectListItem defItem = new SelectListItem { Text = "Select State", Value = "0" };
allItems.Insert(0, defItem);

答案 1 :(得分:0)

好像你过分复杂了。这可能看起来好一点:

model.State = resultSet.Tables[0]
    .OrderBy(x => x.Id)
    .Select(x => new SelectListItem()
        {
            Text = x.Id,
            Value = x.StateName
        }
    ).ToList();

只需将IdStateName替换为您选择的相应列名(使用row.Field<int>(0)row.Field<int>(1))。