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

526

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

一旦我查询了 List<T>,如何将我的初始 Item (不是数据源的一部分)作为该 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;
5个回答

905

使用Insert方法:

ti.Insert(0, initialItem);

能否在列表末尾插入? - Gary Henshall
7
是的,使用Add方法,在末尾插入。 - Martin Asenov
15
自 .NET 4.7.1 版本开始,您可以使用 Append()Prepend() 方法。查看此答案 - aloisdg
对我不起作用 - 无法隐式转换类型“void”为“System.Collections.Generic.List<initialItem>”。 - MC9000
1
这不会替换列表中已经存在的值吗? - Zapnologica
1
不,这并不替换第一项。 - Pieter

43
自.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));

编辑:

如果你想显式地改变给定列表:

// Creating an array of numbers
var ti = new List<int> { 1, 2, 3 };

// mutating ti
ti = ti.Prepend(0).ToList();

但在那个时候,只需使用Insert(0, 0)即可。


根据使用情况而定。在某些情况下,prepend()会做一些其他更好的操作,但在其他情况下可能是不可接受的。 - H H
@HH Prepend() 函数将一个值添加到序列的开头。请注意,原始序列不会被更改。结果是一个全新的序列。Prepend 的文档中提供了许多有用的示例。 - aloisdg
是的,但“全新的序列”不是所要求的。 - H H
@HH 好吧,你仍然可以通过重新分配它来改变列表,但此时最好使用Insert... - aloisdg

26

7

使用 List<T>Insert 方法:

Insert (Int32, T) 方法:在 指定的索引位置 将元素插入 List 中。

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

6

使用 List<T>.Insert

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接