I have the following code. It looks to me like there is a way I could combine it into one statement but I am not sure how to do this.
List<SelectListItem> items = new List<SelectListItem>();
var emptyItem = new SelectListItem(){
Value = "",
Text = "00"
};
items.Add(emptyItem);
ViewBag.AccountIdList = new SelectList(items);
Can someone tell me if it’s possible to simplify this.
Thanks,
Yes, you can use the collection and object initializers together to create the item, add it to the list, and wrap the list all in one statement.
The indentation style above is how I prefer to type it with all the curlies on their own line, but you could even one-line it if you wanted.
Either way it’s a single statement.
And incidentally, since you are just passing the
List<SelectListItem>to aSelectListconstructor, which takes anIEnumerable, you could just pass an array of 1 instead of a list for a bit more performance:Both would work the same in this case, the latter is a bit more efficient, but both are fine and it’s up to you which you prefer. For more info I did a short blog entry comparing different ways to return a single item as an
IEnumerable<T>sequence.