Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Your code has some issues. First, you're reusing the same object for each of your iterations. </p> <p>Consider</p> <pre><code>List&lt;Foo&gt; foos = new List&lt;Foo&gt;(); Foo foo = new Foo(); foo.Bar = "Alpha"; foos.Add(foo); foo.Bar = "Beta"; foos.Add(foo); </code></pre> <p>You will note that your list will have 2 items but they will reference the same object. If you iterate over the list and check <code>Bar</code>, each will return <code>"Beta"</code>. </p> <p>You want to create a <em>new</em> <code>Foo</code> for each item. </p> <pre><code>List&lt;Foo&gt; foos = new List&lt;Foo&gt;(); Foo foo = new Foo(); foo.Bar = "Alpha"; foos.Add(foo); Foo anotherFoo = new Foo(); anotherFoo.Bar = "Beta"; foos.Add(anotherFoo); </code></pre> <p>In looping terms, that basically just means create the object inside the loop instead of outside. </p> <pre><code>while (someCondition) { Foo foo = new Foo(); // do your work, populate the object, etc. // then check contains if (!myList.Contains(foo)) myList.Add(foo); } </code></pre> <p>Regarding checking to see if the collection already contains the object, have you properly overriden <code>Equals</code> and <code>GetHashCode</code>? When dealing the classes, the default behavior is to simply check if the object references are equal. If you're concerned about the <em>values</em> the objects are encapsulating, then you need to provide the logic for that yourself. In your class, you need to override the <code>Equals</code> and <code>GetHashCode</code> methods to implement your desired method of determining equality.</p> <pre><code>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; } } </code></pre> <p>Now when <code>Contains</code> seeks to determine if the object is already in the list, it will do so based upon the the values contained in the object rather than the memory reference.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload