How to invert logical gear array values ​​in C #?

Good afternoon, I have a C # jagged array with true and false values ​​(or 0 and 1), and I want to change the values, for example:

1 1 1 1 0 1 1 0 1 1 1 1 1 0 0 1 

became:

 0 0 0 0 1 0 0 1 0 0 0 0 0 1 1 0 

Is there an easy way to do this without looping it? sort of! myJaggedArray ??

+6
source share
2 answers

There is no built-in operation to invert such an array, but you can use LINQ to invert without explicit loops:

 var res = myJaggedArray.Select(a => a.Select(n => 1-n).ToArray()).ToArray(); 

The triple 1-n is the usual way to replace zeros with ones and ones with zeros without using conditional execution.

+12
source

There is no built-in function, but you can use LINQ.

 int[][] input = new[] { new[] { 1, 1, 1, 1 }, new[] { 0, 1, 1, 0 }, new[] { 1, 1, 1, 1 }, new[] { 1, 0, 0, 1 } }; int[][] output = input.Select(row => row.Select(value => value == 1 ? 0 : 1).ToArray()).ToArray(); 

For boolean values:

 bool[][] input = new[] { new[] { true, true, true, true }, new[] { false, true, true, false }, new[] { true, true, true, true }, new[] { true, false, false, true } }; bool[][] output = input.Select(row => row.Select(value => !value).ToArray()).ToArray(); 
+8
source

All Articles