Home > Net >  Powershell to C# syntax conversion
Powershell to C# syntax conversion

Time:10-09

Can anybody help to convert this Powershell line of code to C#, please?

$query.TextFileColumnDataTypes = ,2 * $worksheet.Cells.Columns.Count

CodePudding user response:

This expression:

,2 * $count

Creates an [int[]] (an array of [int]'s) of length $count where each item has the value initialized to 2.

In C# you could either create the same array with Enumerable.Repeat():

query.TextFileColumnDataTypes = Enumerable.Repeat(2, worksheet.Cells.Columns.Count).ToArray()

Or initialize each item manually:

var array = new int[worksheet.Cells.Columns.Count];
for(int i = 0; i < array.Length; i  )
    array[i] = 2;
query.TextFileColumnDataTypes = array;

CodePudding user response:

To complement Mathias R. Jessen's helpful answer:

  • .NET Core 2.0 / .NET 5 / .NET Standard 2.1 - but not .NET Framework - now offer a convenient static Array.Fill() method:

    var a = new int[3];
    // Note: There is also an overload to target a *subrange*.
    Array.Fill(a, 42);  // -> int[3] { 42, 42, 42 }
    
  • Enumerable.Repeat() is convenient, but slow compared to the for solution.

  • To take the drudgery out of the for solution, you can define an extension method, adapted from this answer.

    public static T[] Fill<T>(this T[] a, T value ) {
      for (int i = 0; i < a.Length;   i) { a[i] = value; }
      return a;
    }
    
    // Sample call:
    var a = new int[3].Fill(42);  // -> int[3] { 42, 42, 42 }
    
  • Related