How to Invoke This c# code?

UiPath removed C# support (see links below) because they couldn’t get it working reliably. Looks like you ran into one of these issues. I would avoid C# until they’re resolved by UiPath.

If you must continue to try to use it, you can remove bits of your code until you find the bit that’s breaking it. Looks like you can also simplify that code quite a bit - try a simple for loop.