将内容添加到列表时出现问题 [英] Problem while adding contents into a list
问题描述
你好朋友,
好吧,我正在使用列表,我试图用两种方法在列表中添加一个元素:
列表< string < span class =code-keyword>> list = new List < string > ();
list1 [index] =Rahul; ///我通过访问索引
list1.Add(Rahul)添加一个元素; ///我使用list.add方法添加元素
现在,有时候我使用其索引访问列表,有时会抛出异常。当我从列表中删除某些内容然后尝试在特定索引处添加项目时会发生这种情况。
现在,我重复了删除项目并添加的相同步骤它使用list.add()。这次没有问题。这是我对列表的全部经验,维护索引非常有问题。
任何建议?
非常感谢Ton,
Rahul
使用插入方法 [ ^ ]
if (index> = 0 && index < list1.Count)
list1.Insert(index, Damith);
Rahul VB写道:当我从列表中删除某些内容然后尝试在特定索引处添加项目时会发生这种情况
当你从列表中删除一个项目时,你不能在其索引上添加另一个项目!
假设一个列表包含:
1。 Adam
2. Eve
3. Maciej
如果第二项已被删除,则列表为:
< pre lang =text> 1。 Adam
2. Maciej
所以...如果你想在2.位置添加新项目,你真的覆盖现有的。
想一想,根据需要更改代码。提示:在列表末尾添加元素,然后移动它。
Hello Friends,
Ok, i was working with lists, i tried to add an element into the list using two methods:
List<string> list = new List<string>();
list1[index] = "Rahul"; ///i add an element by accessing the index
list1.Add("Rahul"); ///I add an element by using the list.add method
Now, some times when i access the list using its index, sometimes an exception is thrown. This happens when i remove something from the list and then try to add an item at a particular index.
Now, I repeated the same procedure of deleting the item and adding it using list.add(). This time no problem occurred. This is my all time experience with lists, maintaining the index is very problematic.
Any suggestions?
Thanks a Ton,
Rahul
Use Insert Method[^]
if(index>=0 && index < list1.Count) list1.Insert(index,"Damith");
Rahul VB wrote:This happens when i remove something from the list and then try to add an item at a particular index
When you remove an item from list, you can't add another one on its index!
Let's say, a list contains:
1. Adam 2. Eve 3. Maciej
If second item has been removed, the list is:
1. Adam 2. Maciej
So... if you're trying to add new item on 2. position, you really overwrite existing one.
Think of it and change code to your needs. Tip: add element at the end of list and then move it.
这篇关于将内容添加到列表时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!