How to add item to the beginning of List?

前端 未结 5 1908
太阳男子
太阳男子 2020-12-04 08:17

I want to add a \"Select One\" option to a drop down list bound to a List.

Once I query for the List, how do I add my in

相关标签:
5条回答
  • 2020-12-04 08:30

    Use Insert method of List<T>:

    List.Insert Method (Int32, T): Inserts an element into the List at the specified index.

    var names = new List<string> { "John", "Anna", "Monica" };
    names.Insert(0, "Micheal"); // Insert to the first element
    
    0 讨论(0)
  • 2020-12-04 08:34

    Use the Insert method:

    ti.Insert(0, initialItem);
    
    0 讨论(0)
  • 2020-12-04 08:37

    Update: a better idea, set the "AppendDataBoundItems" property to true, then declare the "Choose item" declaratively. The databinding operation will add to the statically declared 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

    -Oisin

    0 讨论(0)
  • 2020-12-04 08:42

    Since .NET 4.7.1, you can use the side-effect free Prepend() and Append(). The output is going to be an 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 ));
    
    0 讨论(0)
  • 2020-12-04 08:47

    Use List<T>.Insert

    While not relevant to your specific example, if performance is important also consider using LinkedList<T> because inserting an item to the start of a List<T> requires all items to be moved over. See When should I use a List vs a LinkedList.

    0 讨论(0)
提交回复
热议问题