Adjit
Adjit

Reputation: 10305

Return listBox items from function in C#

I am trying to return the collection list of items in a list box from a function so that I can utilize the data in another function.

I had seen a method to loop through the collection and add it to a list, but is there a better way to do this so I don't have to loop through all of the values in the list?

public list<String> getListItems(){
    List<string> selectedList = new List<string>();
    foreach (var item in listBox1.Items) {
       selectedList.Add(item.ToString());
    }
}

Upvotes: 0

Views: 1503

Answers (3)

Reza Aghaei
Reza Aghaei

Reputation: 125277

You can use Cats<T> this way:

this.listBox1.Items.Cast<Object>().ToList();

Or if you want List<string>:

this.listBox1.Items.Cast<object>().Select(x => x.ToString()).ToList();

Don't forget to add using System.Linq;

Upvotes: 2

Yacoub Massad
Yacoub Massad

Reputation: 27871

You can use LINQ like this:

return listBox1
    .Items
    .Cast<object>()
    .Select(x => x.ToString())
    .ToList();

Although this is less code, I think it is going to be more or less the same performance.

Upvotes: 1

Felipe Oriani
Felipe Oriani

Reputation: 38638

You could try using Cast<> method to convert each item of Items collection to an queryable object.

First add the namespace to use Linq:

using System.Linq;

Try something like this:

public List<string> getListItems()
{
   return listBox1.Items.Cast<object>()
                        .Select(x => x.ToString())
                        .ToList();
}

Upvotes: 1

Related Questions