# Retrieving values from Entity Framework DbContext to render in a ListBox

I need to pass a ViewModel to a strongly typed View which will display a multiple-select box using Html.ListBoxFor. My ViewModel has a List<int> for the selected values and an IEnumerable<SelectListItem> for the options.

Is there a better way I could be enumerating the list of options?

private MyDbContext db = new MyDbContext();

public List<int> SelectedPhysicians { get; set; } = new List<int>(1) { 1 };

public IEnumerable<SelectListItem> AllPhysicians
{
get
{
List<SelectListItem> temp = new List<SelectListItem>();
foreach (PhysicianModel p in db.Physicians)
{
temp.Add(new SelectListItem { Value = p.Id.ToString(), Text = p.Name });
}
return temp;
}
}


Also, can you see any long-term reasons I would even need a List<int> rather than an int[]? I tend to go with List because I almost always end up needing more than basic array operations. In this case, however, I'm just retrieving and storing sets of values in the database.
It's occurred to me that all of my models are using Lists for no tangible reason, but I want to be sure before refactoring.

You might as well just use LINQ to project the collection to SelectListItem
return db.Physicians.Select(new SelectListItem { Value = p.Id.ToString(), Text = p.Name });

Alternatively you can use ICollection<T> as a return type and since most collections implement this interface it doesn't matter what the underlying type is.
• @Sinjai the point of using ICollection or anything higher then a simple IEnumerable means that the collection is already filled. If you return an IEnumerable I'll think it's lazy and will probably call ToList or something to execute it. With EF it's often even more important to not return an IEnumerable if this would be a repository and the query disposes the context. It would fail to execute the query later. Jul 23 '17 at 7:58