0

I have this integer array:

int[] responses = new int[3];

The script then pings an IP address 4 times. If it gets a reply, it adds a "1" to the array. If it does not get a reply, it adds a "0" to the array. I would like to see if the array contains any zeros, and if so, how many. Any ideas on how I could accomplish this?

Matt
  • 93
  • 2
  • 11

2 Answers2

7
int failedResponsesCount = responses.Count(r => r == 0);

I also suggest to use List<bool> to keep history of responses. Because you are adding items to it (btw, with array you can't tell whether 0 was 'added' or it just default value of item). Also you have pretty boolean logic here (you either get reply or not) - you don't need to use integers for representing response type.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
0

Another way ;)

int total = responses.Count(x => x == 0);
if(total > 0)
    //Do something;
else
    //Do something else
Oscar Bralo
  • 1,912
  • 13
  • 12
  • 1
    How is this better than just running `Count` directly and then checking the result? Now you have to iterate the list more than once. – default Mar 03 '14 at 13:50
  • You´re right! I only did it because he asked for that. " I would like to see if the array contains any zeros, and if so, how many. " But as you said, is nt efficient, let me edit – Oscar Bralo Mar 03 '14 at 13:51
  • 1
    Your latest edit doesn't satisfy the 'how many' requirement ;) You could go for `int count; if (count = responses.Count(x => x == 0) > 0)`. – Janis F Mar 03 '14 at 13:54
  • +1 for you Romiox! Thanks for info! Edited! – Oscar Bralo Mar 03 '14 at 13:55