Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert IList<string> to MVC.SelectListItem needs explicit casting

I am calling a project (WCF, but that shouldn't matter) that consumes a IList , with MVC 3 (which really should not matter either obviously) I want to convert a single column List of strings (IList which is just a list of Countries) into a List

Hard Coded list I have done like this and they work fine:

 public List<SelectListItem> mothermarriedatdelivery = new List<SelectListItem>();
 mothermarriedatdelivery.Add(new SelectListItem() { Text = "Yes", Value = "1" });

However, now I am trying to convert this code:

 public List<SelectListItem> BirthPlace { get; set; }
 BirthPlace = new List<SelectListItem>();
 GetHomeRepository repo = new GetHomeRepository();
 BirthPlace = repo.GetCountries();

I need to implicitly convert from the List to SelectListItem, anyone do this? Yes.. I have search and found several examples, but none that really fit my specific need.

like image 818
Tom Stickel Avatar asked Sep 12 '11 19:09

Tom Stickel


1 Answers

You can use LINQ as such:

BirthPlace = repo.GetCountries()
                 .Select(x => new SelectListItem { Text = x, Value = x })
                 .ToList();

Or I think you can just use one of SelectList's constructors:

public SelectList BirthPlace { get; set; }

BirthPlace = new SelectList(repo.GetCountries());
like image 70
Laurent Avatar answered Sep 21 '22 06:09

Laurent