I'm working with a powershell script to try and convert it to a C# program but I have come across a problem I am struggling with. The script uses $NameExample = @()
, which I believe is just an empty array in C# - Something like decimal[] NameExample = new decimal[] {}
.
Here is more of the code to help but I am mainly trying to figure out how to declare $NameExample = @()
as a C# array variable, anything will help!
$counter = 0
$UnitAvgerage = 20
$NameExample=@()
$NameExample2=@()
while ($counter -lt $NameExample.Count)
{
$NameExample2 = $NameExample[$counter..($counter $UnitAvg -1)] | measure-object -average
$counter = $NameExample2
}
CodePudding user response:
Arrays are fixed-size data structures, so they cannot be built up iteratively.
PowerShell makes it seem like that is possible with =
, but what it does behind the scenes is to create a new array every time, comprising the original elements plus the new one(s).
This is quite inefficient and to be avoided, even in PowerShell code (as convenient as it is) - see this answer.
Therefore, in your C# code use an array-like (list) type that you can build up efficiently, such as System.Collections.Generic.List<T>
:
using System.Collections.Generic;
// ...
// Create a list that can grow.
// If your list must hold objects of different types, use new List<object>()
var nameExample= new List<int>();
// ... use .Add() to append a new element to the list.
nameExample.Add(42);