score:8

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

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: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.

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:6

use where.

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

the select() projects each element of a sequence into a new form.

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);

Related Query

More Query from same tag