Reputation: 12304
How can I count elements that are equal to 0
in each array of a list?
I have a list List<byte[]> piks
.
I would like to count in each byte[]
how many elements are with equal to 0
.
I tried a few ways:
from c in piksle_lista_tablic[84]
where (c.Equals(0))
select c
or
piksle_lista_tablic[84].Count(n => n == 0)
and I always get the error Expression cannot contain lambda expressions
.
For example:
piks[1]
is an array containing 1156
items, and I would like to know how many specific elements are in that array.
PS: Can i use Linq in watch window?
Upvotes: 2
Views: 2557
Reputation: 21742
var results = from arr in piks
select arr.Where(b=>b==0).Count()
that code will iterate the list of array and for each array find the elements equalling zero and return an IEnumerable with the counts for each array. I like the where count more than the Count(selector) but that a matter of taste. I doubt there's going to be noticeable difference performancewise
to you ps 1 yes you can use linq while debugging but it's generally a pain because a linq statement is one statement chopping it up in methods can sometimes help while debugging but I dislike writing code for the sake of the debugger.
EDIT As per your comment: No you cannot use Lambda in the watch window. You can use Linq in the watch window but only as method calls and only with named functions
Upvotes: 5
Reputation: 24192
If you want to count the global total, you can do this:
piks.SelectMany(p => p).Count(p => p == 0);
For each array you can do this:
piks.Select(p => p.Count(p => p == 0));
Upvotes: 1
Reputation: 18743
List<byte[]> piks;
// Fill piks...
int zeroValuesCount = 0;
foreach (var pik in piks) {
zeroValuesCount += pik.Count(x => x == 0);
}
Upvotes: 1
Reputation: 838166
Try this:
var zero_counts = piks.Select(p => p.Count(c => c == 0));
ps1. can i try use linq while debug?
Visual Studio doesn't support lambda expressions in the watch window.
Upvotes: 4