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.
1 Answer 1
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 });
As far as lists and arrays are concerned there is actually only one main difference betwen them: arrays cannot change its size. Use what is more conveninet. If you have fixed collection of items the I'd probably use an array an in all other cases I guess I'd chose a list.
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.
-
\$\begingroup\$ I was hoping someone would post LINQ. I'm not very accustomed to it yet, but I figured there had to be a way to use it. Stupid question, but what's even the point of using ICollection? To allow whatever implementation is desired when you ultimately use the property? I've heard to go as general as possible, and intuitively that makes sense, but I couldn't actually tell you why. \$\endgroup\$Sinjai– Sinjai2017年07月22日 11:14:13 +00:00Commented Jul 22, 2017 at 11:14
-
\$\begingroup\$ @Sinjai the point of using
ICollection
or anything higher then a simpleIEnumerable
means that the collection is already filled. If you return anIEnumerable
I'll think it's lazy and will probably callToList
or something to execute it. With EF it's often even more important to not return anIEnumerable
if this would be a repository and the query disposes the context. It would fail to execute the query later. \$\endgroup\$t3chb0t– t3chb0t2017年07月23日 07:58:45 +00:00Commented Jul 23, 2017 at 7:58 -