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



假设我有一个数组

[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

我该怎么做?

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

锯齿形数组通常比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));

假设x和y为二维

和像[x,y]

这样的数组
  1. 初始化x和y为0

  2. 在y的末尾
  3. (当所有的y都被X消耗时),打印a

  4. x递增1

  5. 继续

相关内容

  • 没有找到相关文章

最新更新