C# 将文本文件拆分为二维数组

C# 将文本文件拆分为二维数组,c#,arrays,C#,Arrays,所以我正在做一个小的历史测试来帮助我学习。目前我已经硬编码了数组,这是我想从文本文件中读取数组的方式。我想更改此设置,以便通过更改文本文件来添加和删除日期和事件 static string[,] dates = new string[4, 2] { {"1870", "France was defeated in the Franco Prussian War"}, {"1871", "The German Empire Merge

所以我正在做一个小的历史测试来帮助我学习。目前我已经硬编码了数组,这是我想从文本文件中读取数组的方式。我想更改此设置,以便通过更改文本文件来添加和删除日期和事件

static string[,] dates = new string[4, 2]
        {
            {"1870", "France was defeated in the Franco Prussian War"},
            {"1871", "The German Empire Merge into one"},
            {"1905", "The \"Schliffin PLan\" devised"},
            {"1914", "The Assassination of Franz Ferdinand and the start of WW1"},
            //etc
        }
数组只是一个占位符,用于从文本文件中读取内容。我知道我应该使用StreamReader,然后将其拆分,但我不确定如何执行。我尝试过使用2个列表,然后像这样将它们推到数组中

//for date/event alteration
isDate = true;
//for find the length of the file, i don't know a better way of doing this
string[] lineAmount = File.ReadAllLines("test.txt");
using (StreamReader reader = new StreamReader("test.txt"))
                {

                    for (int i = 0; i <= lineAmount.Length; i++)
                    {
                        if (isDate)
                        {
                            //use split here somehow?
                            dates.Add(reader.ReadLine());
                            isDate = false;
                        }
                        else
                        {
                            events.Add(reader.ReadLine());
                            isDate = true;
                        }
                    }
                }


        string[] dates2 = dates.ToArray();
        string[] events2 = events.ToArray();
        string[,] info = new string[,] { };
        //could use dates or events for middle (they have the same amount)
        //push the lists into a 2d array
        for (int i = 0; i <= events2.Length; i++)
        {
            //gives an index out of bounds of array error
            //possibly due to the empty array declaration above? not sure how to fix
            info[0, i] = dates2[i];
            info[1, i] = events2[i];
        }
//用于日期/事件更改
isDate=真;
//对于查找文件长度,我不知道更好的方法
字符串[]lineAmount=File.ReadAllLines(“test.txt”);
使用(StreamReader=newstreamreader(“test.txt”))
{

对于(inti=0;i来说,这里最大的问题是您试图使用数组来实现这一点。 除非您的程序在开始时知道有多少行,否则它将不知道数组有多大。您必须猜测(最坏情况下容易出错,最好效率低下),或者扫描文件以查找有多少行中断(同样效率低下)

只需使用一个列表,并将您阅读的每一行添加到列表中

如果每个条目的第二部分中没有逗号,那么类似于以下内容的内容可以很好地解析您提到的文件:

List<string[ ]> entries = new List<string[ ]>( );
using ( TextReader rdr = File.OpenText( "TextFile1.txt" ) )
{
    string line;
    while ( ( line = rdr.ReadLine( ) ) != null )
    {
        string[ ] entry = line.Split( ',' );
        entries.Add( entry );
    }
}
如果你想从数组中得到一个随机元素(你说这是一个研究项目),那么你可以这样做:

Random rand = new Random();
while(true)
{
    int itemIndex = rand.Next(0, entries.Length);
    Console.WriteLine( "What year did {0} happen?", entries[itemIndex][1]);
    string answer = Console.ReadLine();
    if(answer == "exit")
        break;
    if(answer == entries[itemIndex][0])
        Console.WriteLine("You got it!");
    else
        Console.WriteLine("You should study more...");
}
var firstYear = events[0][0];
var firstDescription = events[0][1];

读取文件中的所有行,然后在逗号上拆分并将其存储在数组中

//Read the entire file into a string array, with each element being one line
//Note that the variable 'file' is of type string[]
var file = File.ReadAllLines(@"C:\somePath.yourFile.txt");

var events = (from line in file  //For every line in the string[] above
              where !String.IsNullOrWhiteSpace(line)   //only consider the items that are not completely blank
              let pieces = line.Split(',')  //Split each item and  store the result into a string[] called pieces
              select new[] { pieces[0], pieces[1].Trim() }).ToList(); //Output the result as a List<string[]>, with the second element trimmed of extra whitespace
分解它

  • ReadAllLines
    只需打开一个文件,将内容读入数组,然后关闭它

  • LINQ声明:

    • 迭代非空的每一行
    • 拆分逗号上的每一行,并创建一个临时变量(个数)来存储当前行
    • 将拆分行的内容存储在数组中
    • 对每一行执行此操作,并将最终结果存储在一个列表中,这样就有了一个数组列表

假设第二列条目中没有逗号是安全的吗?是的,我忘了这一点!我会很快改变它。如果你只想拆分一个字符,就不需要在
行中构造数组。split()
调用。是的,我差点对此发表了评论,但后来看到你也删除了它。:)你能简单解释一下它是如何工作的吗?我还在学习。首先,整个文件都被读入一个字符串数组(为了将来的参考,除了非常小的文件外,不要这样做)。然后,该数组被送入LINQ查询,该查询过滤掉空行,用逗号分割剩余的行,将它们粘贴在一个2元素数组中,然后将所有这些结果粘贴到一个列表中。结果的结构与我提供的答案完全相同,但到达结果的方式不同。关键点在于,与几乎所有程序一样问一个问题,几乎总是有不止一种方法可以做到。作为程序员,你的工作是决定什么让你的开发速度(通常是linq)、程序速度/效率(通常不是linq)和可读性(这两种方式都可以)达到最佳组合。祝你历史测试好运。;)
var firstYear = events[0][0];
var firstDescription = events[0][1];