Is there some way I could combine this C# code?

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,

Answers


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.

ViewBag.AccountIdList = new SelectList(
    new List<SelectListItem>
    {
         new SelectListItem
         {
            Value = "",
            Text = "00"
         }
    });

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 a SelectList constructor, which takes an IEnumerable, you could just pass an array of 1 instead of a list for a bit more performance:

ViewBag.AccountIdList = new SelectList(
    new []
    {
         new SelectListItem
         {
            Value = "",
            Text = "00"
         }
    });

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.


Need Your Help

EDI Flat File parsing with C#?

c# parsing flat-file edi x12

Initially I was thinking to use SSIS to parse an EDI file, however I've seen a few manual EDI parsers (field mapping), and would like to use automate this functionality in C#.

C# pinvoke structs with union and arrays

c# c++ struct pinvoke unions

im failing to define the correct C# code to work with a C++ library which defines a complex struct with union and arrays, i keep getting some memory exception while executing the C++ code, and im p...