There are some problems in your code. First, you reuse the same object for each iteration.
Consider
List<Foo> foos = new List<Foo>(); Foo foo = new Foo(); foo.Bar = "Alpha"; foos.Add(foo); foo.Bar = "Beta"; foos.Add(foo);
You will notice that your list will contain 2 elements, but they will refer to the same object. If you iterate over the list and check the Bar , each returns "Beta" .
You want to create a new Foo for each item.
List<Foo> foos = new List<Foo>(); Foo foo = new Foo(); foo.Bar = "Alpha"; foos.Add(foo); Foo anotherFoo = new Foo(); anotherFoo.Bar = "Beta"; foos.Add(anotherFoo);
In cyclic terms, this basically means creating an object inside a loop instead of an external one.
while (someCondition) { Foo foo = new Foo(); // do your work, populate the object, etc. // then check contains if (!myList.Contains(foo)) myList.Add(foo); }
As for checking if the collection already contains an object, are you overriding Equals and GetHashCode correctly? When working with classes, the default behavior is to simply check if the references to the objects are equal. If you are worried about the values ββthat objects encapsulate, then you need to provide logic for yourself. In your class, you need to override the Equals and GetHashCode methods to implement the desired method for determining equality.
class Foo { public string Bar { get; set; } public override int GetHashCode() { return this.Bar.GetHashCode(); } public override bool Equals(object other) { Foo otherFoo = other as Foo; if (otherFoo == null) return false; else return this.Bar == otherFoo.Bar; } }
Now, when Contains tries to determine if an object is in the list, it will do this based on the values ββcontained in the object, not the memory reference.