How i can convert IDictionary<Guid,string>
to the IEnumerable<SelectListItem>
? I want to use string as SelectListItem
.
Well you could just use
dictionary.Values().Select(x => new SelectedListItem { Text = x })
Just be aware that it may not be in a useful order: Dictionary<,>
is inherently unordered (or rather, the order may change and shouldn't be relied on).
如果要使用guid作为值,则可以使用
dictionary.Select(x => new SelectListItem { Text = x.Value, Value = x.Key })
Something like this should do what you want:
var selectList = dictionary
.OrderBy(kvp => kvp.Value) // Order the Select List by the dictionary value
.Select(kvp => new SelectListItem
{
Selected = kvp.Key == model.SelectedGuid, // optional but would allow you to maintain the selection when re-displaying the view
Text = kvp.Value,
Value = kvp.Key
})
.ToList();
Using LINQ, you could do something like,
var theSelectList = from dictItem in dict
select new SelectListItem()
{
Text = dictItem.Value,
Value = dictItem.Key.ToString()
};
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.