481

我想将“选择一个”选项添加到绑定到List<T>.

一旦我查询 ,List<T>我如何添加我的初始Item,而不是数据源的一部分,作为其中的 FIRST 元素List<T>?我有:

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

5 回答 5

837

使用插入方法:

ti.Insert(0, initialItem);
于 2008-12-24T00:37:58.590 回答
25

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

-Oisin

于 2008-12-24T00:37:47.030 回答
25

从 .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 ));
于 2020-01-08T10:11:26.043 回答
5

使用Insert方法List<T>

List.Insert Method(Int32, T):Inserts将一个元素插入到List处specified index

var names = new List<string> { "John", "Anna", "Monica" };
names.Insert(0, "Micheal"); // Insert to the first element
于 2018-02-03T06:25:48.967 回答
4

采用List<T>.Insert

虽然与您的具体示例无关,但如果性能很重要,也请考虑使用LinkedList<T>,因为将项目插入 a 的开头List<T>需要将所有项目移到上方。请参阅何时应该使用 List 与 LinkedList

于 2018-11-06T21:11:19.600 回答