将我的List <int>转换为List <SelectListItem>

9 c# asp.net-mvc

我有一个DropDownList包含十年(从2010年到2020年)的范围,如下所示:

var YearList = new List<int>(Enumerable.Range(DateTime.Now.Year - 5, ((DateTime.Now.Year + 3) - 2008) + 1));
ViewBag.YearList = YearList;
Run Code Online (Sandbox Code Playgroud)

但这是我的问题,我希望选择一个默认值,并在我提交信息时保留此值,并希望使用该类型List<SelectListItem>,因为它更实用.

一旦进入这种类型,我将简单地这样做以保持选定的值:

foreach (SelectListItem item in list)
            if (item.Value == str)
                item.Selected = true;
Run Code Online (Sandbox Code Playgroud)

我怎么能把我List<int>变成一个List<SelectListItem>

Use*_*384 12

尝试使用Linq进行转换:

List<SelectListItem> item = YearList.ConvertAll(a =>
                {
                    return new SelectListItem()
                    {
                        Text = a.ToString(),
                        Value = a.ToString(),
                        Selected = false
                    };
                });
Run Code Online (Sandbox Code Playgroud)

然后该项将是SelectListItem的列表


Jas*_*ans 8

您可以使用LINQ将项目从a List<int>转换为a List<SelectListItem>,如下所示:

var items = list.Select(year => new SelectListItem
{
    Text = year.ToString(),
    Value = year.ToString()
});
Run Code Online (Sandbox Code Playgroud)


小智 5

现在有一种更干净的方法可以做到这一点:

SelectList yearSelectList = new SelectList(YearList, "Id", "Description"); 
Run Code Online (Sandbox Code Playgroud)

其中,Id是列表项的值的名称,Description是文本。如果愿意,可以在此之后添加参数以指定所选项目。您所要做的全部传递给您希望转换为选择列表的ICollection!

在您看来,您可以这样做:

@Html.DropDownListFor(m => m.YearListItemId,
                        yearSelectList as SelectList, "-- Select Year --",
                        new { id = "YearListItem", @class= "form-control", @name= 
"YearListItem" })
Run Code Online (Sandbox Code Playgroud)

  • 这应该是答案 - 优秀的答案!( & 干净的!!) (2认同)
  • 问题明确要求 List&lt;int&gt;。List&lt;int&gt; 没有“Id”或“Description”。 (2认同)