1

I have the following function in a library that is being converted to Powershell from C# and I havn't the first clue how to go about translation this statement. I realize SO is not for do a task for me type questions but anyone have any thoughts on where to begin?

IEnumerable<string[]> ReadI3TableString(string sFileData)
{
    var records = sFileData.Split(new[] { (char)05, (char)00 }, StringSplitOptions.RemoveEmptyEntries).Skip(1)
        .Select(line => line.Split(line.ToArray().Where(c => ((Int16)c) >= 128 || ((Int16)c) < 32).ToArray(), StringSplitOptions.RemoveEmptyEntries)).Where(p => p.Length > 1);

    return records;
}
KellCOMnet
  • 1,859
  • 3
  • 16
  • 27

1 Answers1

4

It's not really a "Linq-ish" implementation, rather using Powershell operators and the Powershell pipeline to the same effect:

$records = $fileData -split { $_ -in @([char]0, [char]5) } |
    Select -Skip 1 | 
    Where-Object { 
        ($_ -split { $_ -ge [char] 128 -or $_ -lt 32 }).Count -gt 1
    }

Note: with some sample data I could validate this, but this works with mocked up data I had set up.

WaitingForGuacamole
  • 3,744
  • 1
  • 8
  • 22
  • 2
    Nicely done - I'd almost forgotten that you can pass script blocks to the `-split` operator. While your translation is pretty faithful, the first script block can be avoided in favor of a better-performing `.Split()` _method_ call: `$fileData.Split([char[]] (0, 5), [StringSplitOptions]::RemoveEmptyEntries)`. To emulate `[StringSplitOptions]::RemoveEmptyEntries` with the `-split` _operator_ (currently missing from your answer), use `-ne ''` – mklement0 Apr 22 '21 at 02:28
  • 1
    Yeah, your `Split` implementation is definitely _better_ - because Powershell isn't really Linq-like, I think I had become focused on piped operators as opposed to fluent methods, and tried to minimize the method count as a result. – WaitingForGuacamole Apr 22 '21 at 11:39