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

Ash*_*ine 384 c# generic-list drop-down-menu

我想在绑定到a的下拉列表中添加"Select One"选项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;
Run Code Online (Sandbox Code Playgroud)

Mat*_*ton 662

使用Insert方法:

ti.Insert(0, initialItem);
Run Code Online (Sandbox Code Playgroud)

  • 这个Matt有任何性能影响吗? (12认同)
  • @BrianF,是的你是对的.Doc:[`这个方法是O(n)操作,其中n是Count.](https://msdn.microsoft.com/ru-ru/library/sey5k5z4%28v=vs.110%29.aspx? F = 255&MSPPError = -2147217396) (7认同)
  • 从 .NET 4.7.1 开始,您可以使用“Append()”和“Prepend()”。[检查这个答案](/sf/answers/4175052381/) (7认同)
  • @ 23W如果您要链接到MSDN,您应该链接到英文页面. (3认同)
  • @GaryHenshall是的,使用`Add`方法,它最后插入. (2认同)
  • 不,这不会取代第一项 (2认同)

x0n*_*x0n 23

更新:更好的主意,将"AppendDataBoundItems"属性设置为true,然后以声明方式声明"选择项目".数据绑定操作将添加到静态声明的项目.

<asp:DropDownList ID="ddl" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Value="0" Text="Please choose..."></asp:ListItem>
</asp:DropDownList>
Run Code Online (Sandbox Code Playgroud)

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.appenddatabounditems.aspx

-Oisin

  • 那很酷.OP没有指定ASP.NET,但这是一个很好的技巧. (2认同)
  • 这就是诀窍......比创建自定义元素要容易得多.....谢谢! (2认同)

alo*_*ica 17

从 .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 ));
Run Code Online (Sandbox Code Playgroud)


Sin*_*tfi 8

使用插入方法List<T>

\n\n
\n

List.Insert方法(Int32,\xe2\x80\x82T):将Inserts一个元素插入到List的specified index

\n
\n\n
var names = new List<string> { "John", "Anna", "Monica" };\nnames.Insert(0, "Micheal"); // Insert to the first element\n
Run Code Online (Sandbox Code Playgroud)\n


son*_*nny 7

使用List<T>.Insert

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