Access ListListstring in a Thread

2

I'm using WinForms I can not access a list within a Thread .

This list I already populated it through another method.

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

Edit: Code snippet.

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;
                    }
                }
    
asked by anonymous 05.02.2016 / 23:54

1 answer

4

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

One option you can use is the Count property of 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 (eg, its TextoPublicacao variable), you will have to somehow "join" the strings in your list. The code below uses string.Join to do this, but you may need to use another logic for it.

    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);
            }
        }
    }
    
06.02.2016 / 00:33