2012-05-02 45 views
0

我有以下代碼。它看起來像我可以將它合併成一個聲明,但我不知道如何做到這一點。有什麼方法可以結合這個C#代碼嗎?

List<SelectListItem> items = new List<SelectListItem>(); 

var emptyItem = new SelectListItem(){ 
    Value = "", 
    Text = "00" 
}; 

items.Add(emptyItem); 

ViewBag.AccountIdList = new SelectList(items); 

有人可以告訴我,如果有可能簡化這一點。

感謝,

+1

它取決於你的C#/ .net版本iirc。不知道什麼時候收集和對象初始值設定項被添加... – ChristopheD

+3

那麼,因爲他在上面的代碼中使用了對象初始值設定項,所以假設他在那裏很好,可能是安全的。 –

+0

@JamesMichaelHare:是的,非常真實的評論;-) – ChristopheD

回答

9

是的,你可以使用集合和對象初始化聯手打造的項目,將其添加到列表中,並且所有包裹在一個語句列表。

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

上面的縮進風格是我如何喜歡用自己的行中的所有花括號鍵入它,但你甚至可以一個行,如果你想要的。

無論哪種方式它是一個單一的聲明。

順便一提,因爲你只是過客的List<SelectListItem>SelectList構造函數,它接受一個IEnumerable,你可以只通過,而不是多一點的性能列表1的陣列:

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

兩個在這種情況下工作會相同,後者效率更高一些,但兩者都很好,這取決於您的喜好。欲瞭解更多信息,我做了一個簡短的博客條目比較不同的方式返回single item as an IEnumerable<T> sequence

0

像這樣的東西將是最接近你可以得到它。

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

試試這個:

var items = new List<SelectListItem>() 
{ 
    new SelectListItem { Value = "", Text = "00" } 
} 

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

可讀 可測試,IMO ...但你可以這樣寫:

items.Add(new SelectedListItem(){ 
    Value = "", 
    Text = "00" 
}); 

我不會推薦比這更在一個單一的聲明。這種說法也可以重構爲一個方法接受參數ValueText

// now this is a unit testable method 
SelectedListItem CreateSelectedItem (string value, string text) { 
    return new SelectedListItem(){ 
     Value = value, 
     Text = text 
    }; 
} 

現在你可以寫這在同時更加簡潔它做什麼很清楚的情況如下:

ViewBag.AccountIdList = new SelectList(items.Add(CreateSelectedItem("someValue", "someText")); 
0

ViewBag。 AccountIdList = new SelectList(List items = new List {new SelectListItem {Value =「」,Text =「00」}});

0
ViewBag.AccountIdList = new List<SelectListItem>{new SelectListItem{Value = "", Text = "00"}}; 
相關問題