Click here to Skip to main content
15,879,239 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello Friends,

Ok, i was working with lists, i tried to add an element into the list using two methods:

XML
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
Posted
Comments
Tanuj Rastogi 9-May-14 3:51am    
what is the exception you are getting ?
Rahul VB 9-May-14 4:38am    
Index out of range exception

Use Insert Method[^]
C#
if(index>=0 && index < list1.Count)
  list1.Insert(index,"Damith");
 
Share this answer
 
v2
Comments
Rahul VB 9-May-14 4:48am    
Thanks a ton
Maciej Los 9-May-14 4:53am    
+5Please, see my answer. I added some extra information.
DamithSL 9-May-14 4:58am    
Thanks Maciej
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.
 
Share this answer
 
Comments
Rahul VB 9-May-14 4:47am    
Thanks a ton
Maciej Los 9-May-14 4:53am    
You're very welcome ;)
Call again!
DamithSL 9-May-14 5:01am    
5d!
Maciej Los 9-May-14 5:02am    
Thank you ;)
Jagbir Saini 9-May-14 5:36am    
nyc

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900