Skip to main content
GameDev.net gamedev.net
🔒 Locked

c# array question

Started by TaeKwonDo May 18, 2008 at 9:15 PM 2 replies 750+ views
Original Post
TaeKwonDo
TaeKwonDo
Hi, What would be the easiest way to determine if all the values in an array meet a certain requirement, such as they are all greater than 0? I know theres an All method for arrays but im not sure how it works or if it will be of any help to me. If anyone knows how to do this or has an example of how to do this it would be greatly appreciated:D
jdub
jdub
considering that all the values in this array are ints:

// randomArray is an array of intsforeach (int i in randomArray){   if (i > 0)   {      // do something here   }}


You have to iterate through the array to check all of the values.
J.W.
TaeKwonDo
TaeKwonDo
All right, thats what I figured, just wanted to make sure there wasn't something else out there that might be better.
jpetrie
jpetrie
The All extension method can be used for this in C# 3. For example, given an int[] called list, you can determine if all elements in that list (each element being given the label t) are greater than 0 with:
if( list.All( t => t > 0 ) ) {  ...}


The List method TrueForAll() can be used to do the same thing; it accepts a predicate, so you can use an anonymous delegate. Arrays do not have TrueForAll, however.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.