简体   繁体   中英

Convert my List<int> into a List<SelectListItem>

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

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

But here's my problem, I wish to have a default value selected and keep this value when I submit my information and I wish to use the type List<SelectListItem> for it, since its more practical.

Once in this type I will simply do as such to keep a selected value:

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

How may I convert my List<int> into a List<SelectListItem> ?

Try converting it using Linq:

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

Then the item will be the list of SelectListItem

You can use LINQ to convert the items from a List<int> into a List<SelectListItem> , like so:

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

There is now an even cleaner way to do this:

SelectList yearSelectList = new SelectList(YearList, "Id", "Description"); 

Where Id is the name of the list item's value, and Description is the text. If you like you can add a parameter after this to specify the selected item. All you gotta do it pass in the ICollection that you wish to convert to a select list!

In you view you do this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM