【发布时间】:2009-10-18 21:33:56
【问题描述】:
我需要在集合的开头插入一个对象。
我的收藏是列表类型
我该怎么做?
【问题讨论】:
标签: c# collections
我需要在集合的开头插入一个对象。
我的收藏是列表类型
我该怎么做?
【问题讨论】:
标签: c# collections
在索引 0 处插入一个项目会将插入的对象放在列表的开头,其他项目将向上移动一个。
【讨论】:
我想对其他 cmets 做一点扩展:
您可以使用以下代码在列表的位置 0(或任何给定位置)插入元素:
List<int> myList= new List<int>();
for (int i = 0; i < 1000000; i++)
{
// 0 is the index where you want to insert, i is myobject
myList.Insert(0,i);
}
列表操作是应用程序的主要性能影响之一。
在列表中插入会影响性能。
每当您需要插入时,其他元素都需要移动。The longer your existing list is, the slower it gets.
上面的示例插入函数需要 42 秒(在我的笔记本电脑上)。
相比之下,以下函数需要大约 7 毫秒。
List<int> myList= new List<int>();
for (int i = 0; i < 1000000; i++)
{
myList.Add(i);
}
如果您想稍微测试一下,可以使用以下简单设置:
Stopwatch stopWatch1 = new Stopwatch();
stopWatch1.Start();
// function1 to test
List<int> test = new List<int>();
for (int i = 0; i < 1000000; i++)
{
// 0 is the index where you want to insert, i is myobject
test.Insert(0,i);
}
int[] testArray = test.ToArray();
stopWatch1.Stop();
Stopwatch stopWatch2 = new Stopwatch();
stopWatch2.Start();
// function 2 to test
List<int> test2 = new List<int>();
for (int i = 0; i < 1000000; i++)
{
test2.Add(i);
}
test2.Reverse();
int[] testArra2 = test2.ToArray();
stopWatch2.Stop();
如果您在一个大列表的一行中的 0 处有许多插入,则反转列表、附加所有元素 (`AddRange(MyObject[]') 然后将其反转回来可能会更高效。
// list with Data
List<int> myList = myData.ToList();
// reverse
myList.Reverse();
// effectively insert at 0
for (int i = 0; i < 1000000; i++)
{
myList.Add(i);
}
// reverse the list back so that the given order from before is retained
myList.Reverse();
几乎没有花费额外的时间。
类似地,如果您当前使用以下函数之一遍历您的列表:
// classical for loop
for(int i = 0; i < myList.Length; i++)
{
MyObject objectToProcess = myList[i]
/* do work */
}
// classical foreach loop
foreach(MyObject objectToProcess in myList)
{
/* do work */
}
您不妨使用向后的 for 循环来向后处理列表。这完全抵消了所有性能损失:
for(int i = myList.Length-1; i >= 0; i--)
{
MyObject objectToProcess = myList[i]
/* do work */
}
【讨论】:
当然可以;例如一个通用的字符串列表:
List<string> values = new List<string>();
values.Insert(0, "NewString");
【讨论】:
您可以使用插入方法。
List<string> strings = new List<string> { "B", "C", "D" };
strings.Insert(0, "A");
MSDN 文档:http://msdn.microsoft.com/en-us/library/sey5k5z4.aspx
【讨论】:
看看Insert()方法
myList.Insert(0, [item to insert])
【讨论】: