Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to change tuple values inside of a C# array?

The array I'm using is int[,,] and I want to make the first value of each (what I assume to be) tuple in one method and then I want to modify the second two values several times. (in another method)

For example:

int[,,] MyArrayGet()
{    
    int [,,] myArray;
    int [,,] myArray = new int[9,9,9];
    for (int i = 0; i < 10; i++)
    {
        myArray[i] = [SomeInt,0,0];
    }
    return myArray;
}
int[,,] MyArrayModify(int[,,] myArray)
{   
    for (int i = 0; i < 10; i++)
    {
        if (somthing is true) 
        {
            myArray[i] = [dont change this value,n+1,dont change this value]
        }
        if (somthingelse is true)
        {
            my  Array[i] = [dont change this value,dont change this value,n+1]
    }
}

Is there a quick and easy way to do this?

I have checked this question How to get array of string from List<Tuple<int, int, string>>? however either I do not feel it answers my question.

like image 653
bubblez go pop Avatar asked Jul 21 '16 07:07

bubblez go pop


People also ask

Can you modify values in a tuple?

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.

Can we modify tuple in C#?

Tuple is immutable - you can't modify them.


1 Answers

Tuple by design is immutable. Just create new one when modifying.

IEnumerable<Tuple<int, int, int>> Get()
{
    for (int i = 0; i < 10; i++)
    {
        yield return Tuple.Create(i, 0, 0);
    }
}

IEnumerable<Tuple<int, int, int>> Modify(IEnumerable<Tuple<int, int, int>> tuples)
{
    foreach (var tuple in tuples)
    {
        if (tuple.Item1 < 5)
        {
            yield return Tuple.Create(tuple.Item1, tuple.Item2 + 1, tuple.Item3);
        }
        else
        {
            yield return Tuple.Create(tuple.Item1, tuple.Item2, tuple.Item3 + 1);
        }
    }
}

Your code looks like javascript more than C#. int[,,] is 3D array not array of 3 items.

Tuple<int, int, int>[] is an array of Tuple of 3 items. If you are not a beginner and use LINQ, IEnumerable<Tuple<int, int, int>> is a better version.

like image 139
Tommy Avatar answered Nov 13 '22 07:11

Tommy