Access List<List<string>> in a Thread

Asked

Viewed 160 times

2

I am using Winforms I can’t access a list inside a Thread.

That list I’ve populated it through another method.

If you leave the cursor on top I can see the items, but when I will recover through lstPublicacoes[0].ToString(); I can only visualize the following content. System.Collections.Generic.List1[System.String]

Edit: Excerpt from the code.

List<List<string>> lstPublicacoes = new List<List<string>>();
 string TextoPublicacao="";

                for (int i = 0; i < 20; i++)
                {
                    if (lstPublicacoes[i].ToString() != "")
                    {
                        TextoPublicacao = lstPublicacoes[i].;
                        break;
                    }
                }
  • 1

    You can include the code where you are having this problem?

  • @ carlosfigueira I edited

1 answer

4


You would have the same behavior if you were accessing the list of both the same thread and different threads from where it was created. Your problem is that you are calling the method ToString in a class object List<string>, and it uses the implementation default of this method, returning the class name. Note that as you have a list of lists of strings, an element of your List<List<string>> is a list of strings, and call the method ToString is not the best way to know if the list is empty.

One option you can use is the property Count from the list; if it is non-zero, then the list is not empty. Note that if you want to convert the list of strings into a single string (e.g., its variable TextoPublicacao), you will have to somehow "join" the strings from your list. The code below uses the string.Join to do this, but you may need to use another logic for such.

    static void Main(string[] args)
    {
        List<List<string>> lstPublicacoes = new List<List<string>>();
        lstPublicacoes.Add(new List<string> { "um", "dois", "tres" });
        lstPublicacoes.Add(new List<string> { "onze", "doze", "treze" });
        lstPublicacoes.Add(new List<string> { });
        lstPublicacoes.Add(new List<string> { "vinte e um", "vinte e dois", "vinte e tres" });

        for (int i = 0; i < lstPublicacoes.Count; i++)
        {
            // Imprime System.Collections.Generic.List1[System.String]
            Console.WriteLine(lstPublicacoes[i].ToString());
        }

        for (int i = 0; i < lstPublicacoes.Count; i++)
        {
            if (lstPublicacoes[i].Count != 0)
            {
                string texto = string.Join(", ", lstPublicacoes[i]);
                Console.WriteLine(texto);
            }
        }
    }
  • Carlos, perfect explanation and perfect solution. Solved! Thank you!!

Browser other questions tagged

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