score:8

Accepted answer
int[] a = {1, 2, 3, 0, 5, 0}; 
int x = a.Where(b => b != 0).Count();

score:6

Use Where.

 int x = a.Where(b => b != 0).Count();

The Select() projects each element of a sequence into a new form.

score:3

change this line

 int[] a = {1, 2, 3, 0, 5, 0}; 
 int x = a.Select(b => b != 0).Count();  

to

int[] a = {1, 2, 3, 0, 5, 0}; 
int x = a.Where(b => b != 0).Count(); 

Differnce between

Where

finds items that match and only returns those that do.

-> IEnumerable<A> in, IEnumerable<A> out

Select

returns something for all items in the source. That something might be the items themselves, but are more usually a projection of some sort.

-> IEnumerable<A> in, IEnumerable<B> out

score:2

Your code is just projecting the collection to bools and you get true where the value is not 0 and false where it is, to filer user where

e.g.

int[] a = {1, 2, 3, 0, 5, 0};
int x = a.Where(b => b != 0).Count(); 

score:7

Others have suggested using Where followed by Count, but you can do it even more simply:

int x = a.Count(b => b != 0);

This overload of Count takes a predicate, and basically only counts the elements of the source sequence which match the predicate.

As others have noted, the reason it doesn't work for Select is that that just projects - it doesn't filter. You could use:

// Works but is horrible...
int x = a.Select(b => b != 0).Count(z => z);

... but I'd really suggest you don't.

Note that none of this does what your title talks about, which is finding positive values. For that, you'd want:

int x = a.Count(b => b > 0);

score:2

Your mistake is that {1, 2, 3, 0, 5, 0}.Select(b => b != 0) is just {true, true, true, false, true, false}, which is again 6 items. You can better do with Where instead, which would give you the filtered sequence: {1, 2, 3, 5}. For the resulting sequence you can apply Count or whatever.


Related Articles