Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I believe the following should do the trick:</p> <pre><code>Contract.Requires( Contract.ForAll( coll, obj =&gt; (coll.Where(x=&gt;x.PropA = obj.PropA).Count==1) ) ); </code></pre> <p>The theory is that it filters coll to only those elements whose value of PropA is the same as the object we are looking at. There should only be one of these (itself). </p> <p>You can repeat similarly for B.</p> <p>And it is in theory trivial to combine the ForAll lambda expressions but I'm not sure you'd want to. Surely it would be nice to know which condition fails if one does rather than lumping them all together and knowing that something failed but not really what...</p> <p>If you can give a bit of leeway on the format you can try:</p> <pre><code>Contract.Requires( Contract.ForAll( coll.GroupBy(x=&gt;x.PropA), group =&gt; group.Count==1) ) ); </code></pre> <p>This is a similar principle but I think will do the counting more efficiently since the group by and count will be more efficient (I think - I've not tested and am not famiilar with the inner workings of the linq methods).</p> <p>Another method:</p> <pre><code>HashSet&lt;object&gt; propAValues = new HashSet&lt;object&gt;(); Contract.Requires( !coll.Any(x=&gt;!hashset.Add(x.PropA)) ); </code></pre> <p>This uses a hashset and the fact that Add returns false if the element already exists. In this case the moment an Add generates a false (and thus the lambda expression is true) then Any will return true which since it is negated will fail the test.</p> <p>Whether this method is sensible or not probably depends on how big your objects are (and thus the potential memory implications of doubling up your object set. It will however take least iterations to terminate compared to the other methods here (since the other methods need to look at every object in the collection, potentially several times whereas this last one could potentially stop after looking at two entries).</p>
 

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