6

我有一个项目清单,比如说 100 个项目。我需要在与我的条件匹配的现有元素之前添加另一个元素。最快的方法和最优化的性能是什么?IE。:

foreach (var i in myList)
{
    if (myList[i].value == "myValue")
    {
        myList[i-1] add ("someOtherValue")
    }
}

也许我应该使用其他容器?

4

5 回答 5

14

首先,您可以使用FindIndex方法找到您的项目的索引:

var index = myList.FindIndex(x => x.value == "myvalue");

然后Insert在正确的位置:

myList.Insert(index,newItem);

请注意,在给定索引处插入会推动其他所有内容(考虑在索引 0 处查找您的项目)。

于 2012-11-19T16:49:55.997 回答
4

Consider using a LinkedList<T>. It has the advantage that inserting or removing items does not require shifting any items. The disadvantage is that items cannot be accessed randomly. You have to traverse the list starting at the first or last item in order to access the items.

于 2012-11-19T17:05:55.973 回答
3
myList.Insert(myList.IndexOf("myValue") - 1, "someOtherValue");

您可能应该首先检查以确保 myvalue 存在,并且它不在索引 0 中。

于 2012-11-19T16:48:38.870 回答
3
int index = myList.IndexOf("myValue");
if (index >= 0)
  myList.Insert(index, "myNewValue");

By the way, you should not modify your own collection or list while iterating with for-each (as in your code above).

于 2012-11-19T17:30:23.060 回答
1

我认为列表是一个数组 - 在这种情况下,您是否尝试过使用 Linq 执行此操作?

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直接使用。

于 2012-11-19T16:48:49.150 回答