简体   繁体   中英

how to write value of multi-dimensional array to a text file

let say I have this array

[0,0] = A
[0,1] = B
[0,2] = C
[1,0] = D
[1,1] = E
[1,2] = F
[2,0] = G
[2,1] = H
[2,2] = I
[3,0] = J
[3,1] = K
[3,2] = L

I want them to be written on a text file like this:

A B C
D E F
G H I
J K L

what am I supposed to do?

Jagged arrays are often more convenient than 2D ones.

public static class ArrayExtensions {
  // In order to convert any 2d array to jagged one
  // let's use a generic implementation
  public static T[][] ToJagged<T>(this T[,] value) {
    if (Object.ReferenceEquals(null, value))
      return null;

    // Jagged array creation
    T[][] result = new T[value.GetLength(0)][];

    for (int i = 0; i < value.GetLength(0); ++i) 
      result[i] = new T[value.GetLength(1)];

    // Jagged array filling
    for (int i = 0; i < value.GetLength(0); ++i)
      for (int j = 0; j < value.GetLength(1); ++j)
        result[i][j] = value[i, j];

    return result;
  }
}

so in your case you can convert 2d array into jagged and then use Linq :

var array = new string[,] {
  {"A", "B", "C"},
  {"D", "E", "F"},
  {"G", "H", "I"},
  {"J", "K", "L"},
};

File.WriteAllLines(@"C:\MyFile.txt", array
  .ToJagged()
  .Select(line => String.Join(" ", line));
    static void Main(string[] args)
    {
        var array = new string[4, 3];
        array[0, 0] = "A";
        array[0, 1] = "B";
        array[0, 2] = "C";
        array[1, 0] = "D";
        array[1, 1] = "E";
        array[1, 2] = "F";
        array[2, 0] = "G";
        array[2, 1] = "H";
        array[2, 2] = "I";
        array[3, 0] = "J";
        array[3, 1] = "K";
        array[3, 2] = "L";

        using (var sw = new StreamWriter("outputText.txt"))
        {
            for (int i = 0; i < 4; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    sw.Write(array[i,j] + " ");
                }
                sw.Write("\n");
            }

            sw.Flush();
            sw.Close();
        }
    }

Assume two dimensions x and y.

and an array to be like [x,y]

  1. initiate x and y to 0

  2. increment y one by one [x,y++]

  3. at the end of y(when all y's have been consumed for an X), print a new line character

  4. increment x by one

  5. continue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM