Contracts with C # code - How to ensure that items with unique properties are in a collection of items?

Basically, I have the following:

public class MyClass
{
    public MyClass(ICollection<MyObject> coll)
    {
        Contract.Requires(coll != null);
        Contract.Requires(Contract.ForAll(coll, obj => obj != null));
        Contract.Requires(Contract.ForAll(coll, obj => (????)); //What goes here?
    }
}

public class MyObject
{
    public object PropA { get; set; }
    public object PropB { get; set; }
}

Requirements:

  • All PropA elements in the collection are unique (no duplicates)
  • All PropB items in the collection are unique (no duplicates)

It is impossible to understand what to do here for my operator Contract.ForAll(...).


Bonus: if I can combine operators Contract.ForAll(...)without breaking code contracts?

+5
source share
2 answers

I believe the following should do the trick:

Contract.Requires(
    Contract.ForAll(
        coll, 
        obj => (coll.Where(x=>x.PropA = obj.PropA).Count==1)
    )
);

, coll , PropA , . ().

B.

ForAll, , . , , , , , - , ...

, :

Contract.Requires(
    Contract.ForAll(
        coll.GroupBy(x=>x.PropA), 
        group => group.Count==1)
    )
);

, , , ( - linq).

:

HashSet<object> propAValues = new HashSet<object>();
Contract.Requires(
    !coll.Any(x=>!hashset.Add(x.PropA))
);

hashset , Add false, . , Add (, , ), Any true, , , .

, , , (, , . , ( , , ).

+1

, , , Contract.Requires bool, :

Contract.Requires(coll.GroupBy(o => o.PropA).Count() == coll.Count);

PropB?

+2

All Articles