简体   繁体   English

C# 如何将二维数组中的数据写入文本文件并按列格式化?

[英]C# how can I write data from a two-dimensional array to a text-file and format them in columns?

So I have a two-dimensional array and I want to write all data to a text-file.所以我有一个二维数组,我想将所有数据写入一个文本文件。 But I want them to appear in columns in the text-file.但我希望它们出现在文本文件的列中。

(I haven't declared them like this in my code, but I think this is what the array would look like written out): (我没有在我的代码中这样声明它们,但我认为这是写出数组的样子):

myArray = [{Jamie, 5}, {Susan, 7}, {Robert, 2}, {Sam, 9}];

I want in the text-file it to look like this:我希望在文本文件中它看起来像这样:

Jamie    5
Susan    7
Robert   2
Sam      9

I have looked at other answers such as How to write contents of an array to a text file?我看过其他答案,例如如何将数组的内容写入文本文件? C# and Format a string into columns but I feel like they are only answering half of my question, and I don't understand them either. C#Format a string into columns但我觉得他们只回答了我问题的一半,我也不理解他们。

What I have so far is:到目前为止我所拥有的是:

using (StreamWriter sw = new StreamWriter(@"../../test.txt", false))
{
   foreach ()
   {
   }
}

I'm not sure what I am supposed to have in foreach().我不确定我应该在 foreach() 中有什么。

How do I do this?我该怎么做呢?

One easy way is to:一种简单的方法是:

  1. Iterate all strings you need to output and store the length of the longest one.迭代您需要输出的所有字符串并存储最长字符串的长度。
  2. Iterate again all items;再次迭代所有项目; using two nested loop (rows and columns) seems like a good idea.使用两个嵌套循环(行和列)似乎是个好主意。
  3. Write each item you iterate in step 2 padded to the right with enough whitespaces to account for column spacing and the longest length of step 1. string.PadRight seems like a good option.写下您在第 2 步中迭代的每个项目,并在右侧填充足够的空格以考虑列间距和第 1 步的最长长度。 string.PadRight似乎是一个不错的选择。

You are done.你完成了。

Of couse yo can get fancier and store the longest length of each column and then pad each column with it's specific length...当然你可以变得更漂亮并存储每列的最长长度,然后用它的特定长度填充每列......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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