如何将项目添加到List <t>的开头?</t>

时间:2008-12-24 00:34:38

标签: c# drop-down-menu generic-list

我想在绑定到List<T>的下拉列表中添加“选择一个”选项。

在我查询List<T>后,如何将我的初始Item(不是数据源的一部分)添加为List<T>中的FIRST元素?我有:

// populate ti from data               
List<MyTypeItem> ti = MyTypeItem.GetTypeItems();    
//create initial entry    
MyTypeItem initialItem = new MyTypeItem();    
initialItem.TypeItem = "Select One";    
initialItem.TypeItemID = 0;
ti.Add(initialItem)  <!-- want this at the TOP!    
// then     
DropDownList1.DataSource = ti;

5 个答案:

答案 0 :(得分:620)

使用Insert方法:

ti.Insert(0, initialItem);

答案 1 :(得分:23)

更新:更好的主意,将“AppendDataBoundItems”属性设置为true,然后以声明方式声明“选择项目”。数据绑定操作将添加到静态声明的项目。

<asp:DropDownList ID="ddl" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Value="0" Text="Please choose..."></asp:ListItem>
</asp:DropDownList>

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.appenddatabounditems.aspx

-Oisin

答案 2 :(得分:8)

从.NET 4.7.1开始,您可以使用无副作用的Prepend()Append()。输出将是IEnumerable。

public function product() { return $this->belongsTo(Product::class); }
public function contact() { return $this->belongsTo(Contact::class); }

答案 3 :(得分:1)

使用List<T>插入方法:

  

List.Insert方法(Int32,T):Inserts specified index中列表中的元素。

var names = new List<string> { "John", "Anna", "Monica" };
names.Insert(0, "Micheal"); // Insert to the first element

答案 4 :(得分:1)

使用List<T>.Insert

虽然与您的特定示例无关,但如果性能很重要,则也可以考虑使用LinkedList<T>,因为在List<T>的开头插入项目需要将所有项目移到上方。参见When should I use a List vs a LinkedList

相关问题