How to add item to the beginning of List<T>?

C#Drop Down-MenuGeneric List

C# Problem Overview


I want to add a "Select One" option to a drop down list bound to a List<T>.

Once I query for the List<T>, how do I add my initial Item, not part of the data source, as the FIRST element in that List<T> ? I have:

// 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# Solutions


Solution 1 - C#

Use the Insert method:

ti.Insert(0, initialItem);

Solution 2 - C#

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

Solution 3 - C#

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

Solution 4 - C#

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

Solution 5 - C#

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 https://stackoverflow.com/q/169973/5170571.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAsh MachineView Question on Stackoverflow
Solution 1 - C#Matt HamiltonView Answer on Stackoverflow
Solution 2 - C#aloisdgView Answer on Stackoverflow
Solution 3 - C#x0nView Answer on Stackoverflow
Solution 4 - C#Sina LotfiView Answer on Stackoverflow
Solution 5 - C#sonnyView Answer on Stackoverflow