Reputation: 661
Good afternoon, I have a c# jagged array with true and false values (or 0's and 1's) and I want to reverse the values like:
1 1 1 1
0 1 1 0
1 1 1 1
1 0 0 1
to became:
0 0 0 0
1 0 0 1
0 0 0 0
0 1 1 0
Is there an easy way to do it not looping it? something like !myJaggedArray??
Upvotes: 6
Views: 634
Reputation: 727067
There is no built-in operation for inverting an array like that, but you can use LINQ to do the inversion without explicit loops:
var res = myJaggedArray.Select(a => a.Select(n => 1-n).ToArray()).ToArray();
The 1-n
trick is a common way of replacing zeros with ones and ones with zeros without using conditional execution.
Upvotes: 12
Reputation: 12807
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 logical 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();
Upvotes: 8