2012-05-02 46 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"}}; 
相关问题