我有一个包含100个元素的列表,需要在符合我的条件的现有元素前添加另一个元素。什么是最快速、性能最优化的方法?例如:
foreach (var i in myList)
{
if (myList[i].value == "myValue")
{
myList[i-1] add ("someOtherValue")
}
}
也许我应该使用其他容器?
首先,您可以使用FindIndex
方法查找您的项目的索引:
var index = myList.FindIndex(x => x.value == "myvalue");
然后在正确的位置插入
:
myList.Insert(index,newItem);
考虑使用LinkedList<T>
。它的优点是插入或删除项不需要移动任何项。缺点是无法随机访问项目。您必须从第一个或最后一个项目开始遍历列表才能访问项目。
myList.Insert(myList.IndexOf("myValue") - 1, "someOtherValue");
在使用前,请先检查myvalue是否存在,并且它不在索引0处。
List<string>
,并且 OP 的项具有 value
属性,这意味着它是自定义类型。 - Jamiecint index = myList.IndexOf("myValue");
if (index >= 0)
myList.Insert(index, "myNewValue");
string[] mylist = new string[100];
// init the list
List<string> list = keys.ToList();
list.Insert(1,"somethingelse");
mylist = list.ToArray(); // convert back to array if required
List
),你可以跳过转换步骤,直接使用Insert
。