Load list from txt in C #

1

I have the following problem, I get the data of a txt that I need to return in the form of List<List<string>> , however I can only get txt from a string [] linha , so I was adding string per string in my list, this it works, however each time the new list is added, the same values are added again in the same list, follow the code.

   public List<List<string>> carregaHistoria( string nomeHistoria ){

      List<List<string>> historia = new List<List<string>> () {} ;

      List<string> listaIntermediaria = new List<string>(){};

      FileInfo theSourceFile =
            new FileInfo ( Application.persistentDataPath + "/" + nomeHistoria + ".txt");

      StreamReader reader = theSourceFile.OpenText();

      string text;

      string [] linha;

      do
      {
         linha = reader.ReadLine().Split('|');

         text = reader.ReadLine();

         for(int j = 0; j < linha.Length ; j++){

            listaIntermediaria.Add(linha[j]) ;
         }

         historia.Add( listaIntermediaria );

         //listaIntermediaria.Clear();

      } while (text != null);

      return historia;
   } 

Example of what happens to be clearer: if in my txt I have:

"alguma coisa|outra coisa"
"mais uma coisa|mais outra coisa"
"que coisa|mais coisa"

In my final list I will have all the rows in the first position of the list, the first two rows in the second position, and only the first row in the third position of the list, that was the result I got. And I tried to add the command listaIntermediaria.Clear(); , but then the list goes completely empty all the time.

    
asked by anonymous 30.11.2017 / 00:04

1 answer

1

A minimal example would be:

List<List<string>> lista = new List<List<string>>();
lista.Add("1|2|3".Split("|").ToList());

That is, in the text found on each line I would do split and finally the ToList() method to add in List<List<string>> .

In your code use something like this:

public List<List<string>> carregaHistoria( string nomeHistoria )
{
    List<List<string>> historia = new List<List<string>>();

    FileInfo theSourceFile = 
           new FileInfo ( Application.persistentDataPath + "/" + nomeHistoria + ".txt");

    using (StreamReader reader = theSourceFile.OpenText())
    {

        string line;

        while ((line = reader.ReadLine()) != null)
        {
            historia.Add(line.Split('|').ToList());
        }   

    }

    return historia;

}
    
30.11.2017 / 01:19