John Smith
John Smith

Reputation: 1793

List Foreach returning booleans

I have a simple list of integers:

List<int> ints = new List<int>{1,2,3,4,5};

Is there any way how to check a constraint like this :

bool result = ints.ForEach(x=>x > 0);

so the result would be true if each number in the list is bigger than 0 and false if any number from the list would be less than 0.

Any idaes?

Thanks

Upvotes: 0

Views: 1670

Answers (1)

juju
juju

Reputation: 449

Use the IEnumerable<T>.All extension method, which returns true if all elements of a sequence satisfy a condition:

List<int> ints = new List<int> { 1, 2, 3, 4, 5 };
bool result = ints.All(x => x > 0); // true if all items are > 0

Upvotes: 1

Related Questions