Convert my list <int> to list <SelectListItem>

I have a DropDownList containing a range of ten years (from 2010 to 2020) created as follows:

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

But here is my problem, I want to select the default value and save this value when I send my information, and I want to use the List<SelectListItem> type for it, since it is more practical.

As soon as in this type I will just do so to save the selected value:

 foreach (SelectListItem item in list) if (item.Value == str) item.Selected = true; 

How to convert my List<int> to List<SelectListItem> ?

+6
source share
2 answers

Try converting it with Linq:

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

Then the item will be a SelectListItem list.

+9
source

You can use LINQ to convert elements from List<int> to List<SelectListItem> , for example:

 var items = list.Select(year => new SelectListItem { Text = year.ToString(), Value = year.ToString() }); 
+6
source

All Articles