Why does adding to an ArrayList count whats being passed to it?

Viewed 91

Hello and good evening to yall

I was looking to see if I can get some assistance in suppressing the count when adding to ArrayList. For some reason I dont understand even after my google searches, I just can't suppress the count.

[System.Collections.ArrayList]$AStuff = @()
[System.Collections.ArrayList]$CStuff = @()
[System.Collections.ArrayList]$Rest = @()

switch -Wildcard (gci C:\users\abrah\OneDrive\Desktop){
    "D*" {$AStuff.Add($_)}
    "C*" {$CStuff.Add($_)}
    Default {$Rest.Add($_)}
    }

for($i=0; $i -lt ($AStuff.Count + $CStuff.Count + $Rest.Count); $i++){
    [pscustomobject]@{
        "Letter A" = $AStuff[$i]
        "Letter C" = $CStuff[$i]
        "Rest " = $Rest[$i]
    }
}

the output is:


0
1
0
1
0
1
2
3
2
3
4

Letter A Letter C                  Rest                            
-------- --------                  -----                           
dir1     CFR-2008-title38-vol1.pdf Test                            
dir2     cs.csv                    v1                              
         CSV                       error.png                       
         csvv.csv                  Screenshot 2021-01-09 195943.png
                                   v2.pdf                          
                                                 

Can someone educate me on what is going on in regards to why it outputs the count?

Please dont feel the need to answer if its something really simple, a brief explanation will do and I should be able to fix it if thats the case.

  • On a side note, is there a more efficient way to add to an object like its shown above?
1 Answers

This is just because Add method returns an int :

$a =@()
$a.Add

OverloadDefinitions                 
-------------------                 
int IList.Add(System.Object value) 

So in you case you can avoid it using | out-null.

$AStuff.Add($_) | out-null
Related