How to iterate through two dimensional array
I have two list that I convert them to a single two dimesnional array like this:
double[,] data = new double[voltage.Count(), 2];
for (int i = 0; i < voltage.Count(); i++)
{
data[i, 0] = voltage[i];
data[i, 1] = current[i];
}
Now I am trying to itterate through this array but what I get is same value for both voltage and current in each line:
foreach (double data in ztr.GetCurveDataForTestType()) //this will return my array
{
richTextBox1.AppendText("Voltage" + data + " --------- ");
richTextBox1.AppendText("Current" + data + "\r\n");
}
Voltage-0.175 --------- Current-0.175
Voltage-9.930625E-06 --------- Current-9.930625E-06 Voltage-0.171875 --------- Current-0.171875 Voltage-9.53375E-06 --------- Current-9.53375E-06 Voltage-0.16875 --------- Current-0.16875
As you see in the first line both voltage and开发者_开发技巧 current are same value that is voltage, and on the second raw they are the same again but this time it is the current value. How can I fix this?
I'd recommend not using multi-dimensional arrays for this.
Instead you can make a class something like this:
class Measurement
{
public double Voltage { get; set; }
public double Current { get; set; }
}
And change your method to return IEnumerable<Measurement>
. In .NET 4.0 you can use Zip
:
public IEnumerable<Measurement> GetCurveDataForTestType()
{
return voltage.Zip(current,
(v, c) => new Measurement { Voltage = v, Current = c});
}
And for older versions of .NET:
public IEnumerable<Measurement> GetCurveDataForTestType()
{
for (int i = 0; i < voltage.Count(); i++)
{
yield return new Measurement
{
Voltage = voltage[i],
Current = current[i]
};
}
}
Then your code becomes:
foreach (Measurement data in ztr.GetCurveDataForTestType())
{
richTextBox1.AppendText(
"Voltage: {0} --------- Current: {1}", data.Voltage, data.Current);
}
You use the same kind of loop as when you created the array:
for (int i = 0; i < data.GetLength(0); i++) {
richTextBox1.AppendText("Voltage" + data[i, 0] + " --------- ");
richTextBox1.AppendText("Current" + data[i, 1] + "\r\n");
}
Update: This question appears to be a duplicate of How to foreach through a 2 dimensional array?. The linked answer has an alternate solution that enables the use of foreach by switching from a two-dimensional array to an array of array.
foreach
with a two dimensional array, will sequentially return every double value in the array (by design).
For example, given the following two-dimensional array of doubles:
var array = new double[,] { { 0, 1, }, { 2, 3 }, { 4, 5 } };
foreach (var d in array)
{
Console.WriteLine(d);
}
You will get the following Console output:
0
1
2
3
4
5
Therefore, foreach is not appropriate for you needs. You should use a for
loop.
精彩评论