问题
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.
回答1:
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.
回答2:
You have to replace the tuple you want to modify by a new tuple containing the updated value. Alternatively, you can create a class with the fields that you need and public properties. That will only take seconds and probably make your code more readable.
来源:https://stackoverflow.com/questions/38498151/is-there-a-way-to-change-tuple-values-inside-of-a-c-sharp-array