【问题标题】:How to add item to the beginning of List<T>?如何将项目添加到 List<T> 的开头?
【发布时间】:2010-09-28 06:38:32
【问题描述】:

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

查询List&lt;T&gt; 后,如何将我的初始Item(不是数据源的一部分)添加为List&lt;T&gt; 中的第一个元素?我有:

// 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;

【问题讨论】:

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


    【解决方案1】:

    使用Insert 方法:

    ti.Insert(0, initialItem);
    

    【讨论】:

    • @BrianF,是的,你是对的。文档:This method is an O(n) operation, where n is Count.
    • @23W 如果您要链接到 MSDN,您可能应该链接到英文页面。
    • @GaryHenshall 是的,使用Add 方法,它插入到最后。
    • 从 .NET 4.7.1 开始,您可以使用Append()Prepend()Check this answer
    • 这是否会替换列表中已有的现有值?
    【解决方案2】:

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

    <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

    -奥辛

    【讨论】:

    • 这很酷。 OP 没有指定 ASP.NET,但这是一个很好的技巧。
    【解决方案3】:

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

    // Creating an array of numbers
    var ti = new List<int> { 1, 2, 3 };
    
    // Prepend and Append any value of the same type
    var results = ti.Prepend(0).Append(4);
    
    // output is 0, 1, 2, 3, 4
    Console.WriteLine(string.Join(", ", results ));
    

    【讨论】:

    • 这个解决方案在使用 enumerable 时是最好的
    • 所有列表都实现了 IEnumerable,但是 prepend 和 append 都将返回一个 IEnumerable。这可能是也可能不是您想要的。
    【解决方案4】:

    使用List&lt;T&gt;插入方法:

    List.Insert 方法 (Int32, T):Inserts 将一个元素插入到 specified index 的 List 中。

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

    【讨论】:

      【解决方案5】:

      使用List&lt;T&gt;.Insert

      虽然与您的具体示例无关,但如果性能很重要,还可以考虑使用 LinkedList&lt;T&gt;,因为将项目插入到 List&lt;T&gt; 的开头需要移动所有项目。见When should I use a List vs a LinkedList

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-23
        相关资源
        最近更新 更多