List.Add seems to be duplicating entries. What's wrong?

Solution 1:

Given the signature of your addToList method:

public void addToList(myOtherClass tmp)
  {
    anewList.Add(tmp);
  }

Is is possible that in the consumer of that method, you aren't actually creating a new instance?

You said that you are calling addToList 100 times. Presumably, that is in a loop. At each loop iteration, you will need to create a new instance of "myOtherClass", otherwise, you'll just be updating the same object in memory.

For example, if you do the below, you will have 100 copies of the same object:

myOtherClass item = new myOtherClass();

for(int i=0; i < 100; i++)
{
  item.Property = i;
  addToList(item);
}

However, if your loop looks like the below, it will work fine:

myOtherClass item = null;
for(int i=0; i < 100; i++)
{
  item = new myOtherClass();
  item.Property = i;
  addToList(item);
}

Hope that helps!

Solution 2:

In this case, it would likely be helpful to see how you are validating each item to be sure that the items are unique. If you could show the ToString() method of your class it might help: you might be basing it on something that is actually the same between each of your objects. This might help decide whether you really are getting the same object each time, or if the pieces under consideration really are not unique.

Also, rather than accessing by index, you should use a foreach loop whenever possible.

Finally, the items in a list are not universally unique, but rather references to an object that exists elsewhere. If you're trying to check that the retrieved item is unique with respect to an external object, you're going to fail.

One more thing, I guess: you probably want to have the access on anewList to be private rather than public.

Solution 3:

Try iterating through the list using foreach rather than by index. I suspect that the problem is in the code that you have omitted from your example, not the list itself.

foreach (MyOtherClass item in tmpClass.anewList)
{
     Console.WriteLine( item );  // or whatever you use to write it
}

EDIT

Have you examined the list structure in the debugger to ensure that your unique items are actually added? Also, you might want to use .Count (the property) instead of .Count() (the extension method). The extension method may actually iterate over the list to count the methods, while the property is just looking up the value of a private variable that holds the count.

@James may be onto something here. If you are just changing the properties of the item you've inserted and reinserting it, instead of creating a new object each time, this would result in the behavior you are seeing.

Solution 4:

Well, from I've read here, I supose your problem could be in adding items in list - are you sure, you're not adding the same reference again and again? That could be reason, why you have 100 "last items" in list.