如何在List<>中插入元素

时间:2016-06-07 07:44:27

标签: c# list

我有一个像这样的列表

var mylist = new List<string>();
mylist.Add("apple");
mylist.Add("orange");
mylist.Add("banana");
mylist.Add("mango");

现在我想在橙色香蕉之间添加&#34;甜瓜&#34; ?我怎样才能做到这一点?感谢。

2 个答案:

答案 0 :(得分:4)

您可以使用Insert方法在列表中插入新项目。此方法的第一个参数是Index,其次是item

因此,如果您需要在orange旁边插入,则需要找到index of orange并使用IndexOf橙色插入旁边。

mylist.Insert((mylist.IndexOf("orange") + 1), "melon");

答案 1 :(得分:1)

使用List<T>.Insert()

mylist.Insert(2, "melon");

第一个参数是应该插入字符串的索引。