La forma más sucinta de convertir ListBox.elementos de una lista genérica


Estoy usando C# y dirigiéndome a.NET Framework 3.5. Estoy buscando un código pequeño, sucinto y eficiente para copiar todos los elementos de un ListBox a un List<String> (Genérico List).

En este momento tengo algo similar al siguiente código:

        List<String> myOtherList =  new List<String>();
        // Populate our colCriteria with the selected columns.

        foreach (String strCol in lbMyListBox.Items)
        {
            myOtherList.Add(strCol);
        }

Que funciona, por supuesto, pero no puedo evitar tener la sensación de que debe haber una mejor manera de hacer esto con algunas de las características del lenguaje más nuevas. Estaba pensando en algo como List.ConvertAll método pero esto solo se aplica a Listas Genéricas y no ListBox.ObjectCollection colecciones.

Author: jamiei, 2009-10-14

5 answers

Un poco de LINQ debería hacerlo: -

 var myOtherList = lbMyListBox.Items.Cast<String>().ToList();

Por supuesto, puede modificar el parámetro Type del Cast a cualquier tipo que haya almacenado en la propiedad Items.

 95
Author: AnthonyWJones,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-14 10:51:34

Lo siguiente lo hará (usando Linq):

List<string> list = lbMyListBox.Items.OfType<string>().ToList();

La llamada OfType se asegurará de que solo se utilicen elementos en los elementos del listbox que sean cadenas.

Con Cast, si alguno de los elementos no son cadenas, obtendrá una excepción.

 27
Author: adrianbanks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-14 10:48:43

¿qué tal esto:

List<string> myOtherList = (from l in lbMyListBox.Items.Cast<ListItem>() select l.Value).ToList();
 5
Author: DavidGouge,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-14 10:44:41

¿Qué pasa con:

myOtherList.AddRange(lbMyListBox.Items);

EDITAR basado en comentarios y la respuesta de DavidGouge:

myOtherList.AddRange(lbMyListBox.Items.Select(item => ((ListItem)item).Value));
 2
Author: Konamiman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-14 10:55:37

No necesitas más. Obtiene la Lista de todos los valores de Listbox

private static List<string> GetAllElements(ListBox chkList)
        {
            return chkList.Items.Cast<ListItem>().Select(x => x.Value).ToList<string>();
        }
 1
Author: iruisoto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-27 16:37:51