Neil P
Neil P

Reputation: 3190

Can I use the .Min() Linq extension method on a bool type?

I want to find if I have any bools that are false in a collection. Can I use the following code to find it?

this.MyList.Min(e => e.MyBool)

I'm hoping this will return false if there is a false in the collection.

Upvotes: 3

Views: 1842

Answers (2)

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51330

Yes, it will work because Boolean is IComparable<Boolean> but it's awkward and thus it's harder to understand the intent of your code.

Additionally, your code will have to go through the whole sequence just to find out if there's a false, and it will throw if the sequence is empty.

Use All instead:

MyList.All(item => item.MyBool)

This will return false if there's any false value in the sequence. If the sequence is empty, All will return true.

Upvotes: 5

Tim Schmelter
Tim Schmelter

Reputation: 460068

You can use (renamed the collection for reasons of readability):

bool anyFalse = myBools.Any(b => !b);

or

bool anyFalse = !myBools.All(b => b);

both are efficient since they break on the first false.

If there are complex objects in the collection(as it seerms to be) use:

bool anyFalse = MyList.Any(x => !x.MyBool);

or

bool anyFalse = !MyList.All(x => x.MyBool);

Upvotes: 14

Related Questions