Load list from txt in c#

Asked

Viewed 346 times

2

I have the following problem, I get the data from a txt that I need to return in the form of List<List<string>>, but I can only catch from the txt one string [] linha, so I was adding string by string in my list, it works, but every time the new list is added, the same values are added once more in the same list, it follows 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 make it 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 lines in the first position of the list, the first two lines in the second position, and only the first line 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 is completely empty all the time.

  • the first line has two text, the second line has two text is this ??? you want as a result, 3 lines and each line with two texts?

1 answer

1


A minimal example would be:

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

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

In your code you 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;

}
  • I didn’t understand exactly what happened, because when I tried to fix my function by adding . Tolist(), in mine I gave an error saying that . Tolist() wasn’t valid, but then I copied and pasted your code and it worked Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.