secondplace
secondplace

Reputation: 588

Powershell how to count all elements in a multidimensional array

I've been trying to figure out how to count all elements in an multidimensional array. But .Count only returns the first dimension.

after i gave up to find a proper solution i just created this loop to move all elements to the first dimension and count them. but this is really only a hack.

$mdarr = @((0,1,2,3,4),(5,6,7,8,9),(10,11,12,13,14))
$filecount = New-Object System.Collections.ArrayList
for($i = 0; $i -lt $mdarr.Length; ++$i) {
        $filecount += $mdarr[$i]
}
$filecount.Count

How would this be done properly without processing the array first?

Upvotes: 0

Views: 3048

Answers (3)

user15141832
user15141832

Reputation: 1

put a dimension identifier index in front of .count

e.g $xs[0].count

this way, instead of returning the count of dimensions, it returns the number of rows for a given dimension

Upvotes: 0

crisc2000
crisc2000

Reputation: 1222

one line code: you can flatten the multidimensional array into a anonymous array, and count the anonymous array

$xs = @((0,1,2,3,4),(5,6,7,8,9),(10,11,12,13,14))
@($xs | ForEach-Object {$_}).count #result 15

or multiline that is more readable:

$xs = @((0,1,2,3,4),(5,6,7,8,9),(10,11,12,13,14))
$xs_flatten = @($xs | ForEach-Object {$_})
$xs_flatten_count = $xs_flatten.count
echo $xs_flatten_count #result 15

Upvotes: 0

Micha Wiedenmann
Micha Wiedenmann

Reputation: 20843

In the loop you are adding the elements of $mdarr[$i]. You later count the elements of the merge result. Instead of the adding to an ArrayList you could keep a count:

$xs = @((0,1,2,3,4),(5,6,7,8,9),(10,11,12,13,14))
$sum = 0;
foreach ($x in $xs) { $sum += $x.Count }
$sum  // 15

# alternatively
$xs | % { $sum += $_.Count }

# or
($xs | % { $_.Count } | Measure-Object -Sum).Sum
# or
$xs | % { $_.Count } | Measure-Object -Sum | select -Expand Sum

Upvotes: 1

Related Questions