如何将多维数组的值写入文本文件

时间:2015-08-14 05:21:15

标签: c# multidimensional-array io text-files

假设我有这个数组

[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

我希望将它们写在这样的文本文件中:

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

我该怎么做?

3 个答案:

答案 0 :(得分:3)

Jagged 数组通常比 2D 数组更方便。

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;
  }
}

因此,在您的情况下,您可以将 2d 数组转换为锯齿状,然后使用 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));

答案 1 :(得分:2)

假设x和y两个维度。

和一个数组类似于[x,y]

  1. 将x和y启动为0

  2. 逐一递增y [x,y ++]

  3. 在y的结尾(当X已经消耗了所有y时),打印a 新行字符

  4. 将x增加一个

  5. 继续

答案 2 :(得分:2)

    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();
        }
    }