Check collections

Oct 22, 2010 at 8:54 AM

Hi,
Is there a way to elegantly check if a collection of objects is not nothing, contains at least one element, and if a certain property of an/any/all element has a certain value?

Something like:
MyCollection.Should.
  Not.Be.Null.
  And.Not.Be.Empty.
  And.Satisfy(f => f.Should.Have.ValueOf.MyProperty = MyValue)

thanks
pascal

Coordinator
Oct 24, 2010 at 1:36 PM

(new[] {4, 2, 5}).Satisfy(x => x.Any(a => a < 3));

"Any" mean "at least one" so using the satisfier is enough to understand the sentence.

 

(new[] {4, 2, 5}).All(x => x.Satisfy(a => a > 3));

Using this syntax for "All", you will have the exact element which not satisfies the assertion.

In this case the failure message is:

2 Should Satisfy (a => a > 3)
Compared values was: 2 > 3.

 

To work with exact number of members:

(new[] {4, 2, 5}).Satisfy(x => x.Count(a=> a < 3) == 7);

In this case the failure message is:

[4, 2, 5] Should Satisfy (x => x.Count(a => a < 3) == 7)
Compared values was: 1 == 7.

 

 

 

 

Oct 25, 2010 at 8:11 AM

Thanks for the answer. But my question was more like how can a use this together with a check if the collection instance is null?

thanks
pascal

Coordinator
Oct 25, 2010 at 12:15 PM

You can do it in two lines; the first checking for Not.Null() the second checking for the content.

btw you can check directly for the content because where the instance is null or empty the assertion will fail.