Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Powershell to C#

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
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading