0

I have a 2D array of floats and I want to convert it into 1D array of strings, where each string is one row of elements from 2D array. I am not getting output in text file as I expected. Can anyone tell me what I'm doing wrong? It will be great help to me, if somebody could provide efficient code with corrections.

string[] set = new string[240];

string value = "@"

for (int i = 0; i < 240; i++)
{
    for (int j = 0; j < 320; j++)
    {
        value = Convert.ToString(ImageArray[i, j]);
        value += ",";
    }

    set[i] = value + Environment.NewLine;
    value = " ";
}

for(int k=0;k<240;k++)
{
    System.IO.File.AppendAllText(@"C:\Users\mtech\Desktop\sathya.txt", set[k]);
    textBlock1.Text = set[k];
    value = " ";
}

3 Answers 3

4

inside your inner for loop(j), you are overwriting the value of value variable.

i.e.

for (int j = 0; j < 320; j++)
    {
        value = Convert.ToString(ImageArray[i, j]);
        value += ",";
    }

instead of above, you should be doing:

for (int j = 0; j < 320; j++)
    {
        value += Convert.ToString(ImageArray[i, j]) +",";
    }

also, you don't need to perform two nested loops for this task, take a look at String.Join

Sign up to request clarification or add additional context in comments.

1 Comment

yeah !! i realized the mistake after i posted the code, thanks a lot
2

Here is the shorter way with LINQ:

var allValues = ImageArray.OfType<float>();
string[] lines = new string[240];
for(int i=0; i<240; i++)
{
   lines[i] = string.Join(",", allValues.Skip(i*320).Take(320));
}

 File.AppendAllLines(@"C:\Users\mtech\Desktop\sathya.txt", lines);

Comments

1

You're re-assigning value in every iteration in your nested for loop. Use the += operator, instead. Another thing you should consider is the use of StringBuilder if you're going to repeatedly append to a string. strings are immutable so you're actually creating a new string every time you append to it.

Not sure if this applies to your case (because of the boundaries in your for loops), but you can use LINQ to flatten a multidimensional array. Example:

float[,] arr = new float[2,2]
{
    {123.48F, 45.3F},
    {954.23F, 91.3F}
};

var str = string.Join("",
              arr.Cast<float>()
             .Select(x => Convert.ToString(x) + ","));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.