首页 文章

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

提问于
浏览
324

我想在绑定到 List<T> 的下拉列表中添加"Select One"选项 .

一旦我查询 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;

4 回答

  • -1

    使用Insert方法:

    ti.Insert(0, initialItem);
    
  • 578

    更新:更好的主意,将“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

  • 22

    使用 List<T>Insert 方法:

    List.Insert方法(Int32,T):在指定索引处将元素插入List .

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

    使用 List<T>.Insert

    虽然与您的具体示例无关,但如果性能很重要,请考虑使用 LinkedList<T> ,因为将项目插入 List<T> 的开头需要移动所有项目 . 见When should I use a List vs a LinkedList .

相关问题