Nuts
Nuts

Reputation: 2813

Change sign of all values in a two-dimensional array for the specific dimension

How to change sign of all numbers in a two-dimensional array for the specific dimension ?

I have for example object[,] that is filled with value, like

[0,1]
[0,2]
[0,3]

I want to change the sign for all the values in the second dimension to get

[0,-1]
[0,-2]
[0,-3]

What is the way to do this efficiently with small amount of code?

I started to think foreach for each item but I'm lost already here

object[,] values = new object[1, 100];
foreach (object[,] v in values )
    {

    }

Upvotes: 0

Views: 195

Answers (2)

Arash Motamedi
Arash Motamedi

Reputation: 10672

Is the 2-Dimensional object array object[,] a requirement, or can you represent your data in an easier to work with int[][] structure? Something like:

int[][] matrix = new[]
{
    new[] {0, 1, 2},
    new[] {0, 2, 4},
    new[] {0, 3, 9}
};

Then you can create your desired transform like this:

int columnToFlip = 1;
IEnumerable<IEnumerable<int>> flipped = matrix.Select(row => row.Select((value, index) => index == columnToFlip ? -value : value));

Or, if you need the result in an int[][] array, then:

int[][] flippedMatrix = matrix.Select(row => row.Select((value, index) => index == columnToFlip  ? -value : value).ToArray()).ToArray();

C# Lambda Expressions and Enumerable Extension Methods are powerful tools for transforming, filtering, ordering, joining, aggregating, grouping, and projecting data.

Upvotes: 0

Zohar Peled
Zohar Peled

Reputation: 82474

Here is one way to do it:

object[,] values = new object[1,10];

for (var i = 0; i < values.GetLength(0);i++) 
{
    for (var j = 0; j < values.GetLength(1); j++)
    {
        var obj = values[i, j];
        int intVal;
        if (obj != null && int.TryParse(obj.ToString(), out intVal))
        {
            values[i, j] = -1 * intVal;
        }
    }
}

However, if you would use an array of ints, your code would look like this:

int[,] values = new int[1, 10];

for (var i = 0; i < values.GetLength(0); i++)
{
    for (var j = 0; j < values.GetLength(1); j++)
    {
            values[i, j] = -1 * values[i, j];
    }
}

Upvotes: 1

Related Questions