Casting an Item Collection from a listbox to a generic list
Asked Answered
J

3

46

I want to find a better way of populating a generic list from a checkedlistbox in c#.

I can do the following easily enough:

List<string> selectedFields = new List<string>();

foreach (object a in chkDFMFieldList.CheckedItems) {
         selectedFields.Add(a.ToString());
         } 

There must be a more elagent method to cast the CheckedItems collection to my list.

Jumpoff answered 23/1, 2009 at 1:54 Comment(0)
C
70

Try this (using System.Linq):

OfType() is an extension method, so you need to use System.Linq

List<string> selectedFields = new List<string>();
selectedFields.AddRange(chkDFMFieldList.CheckedItems.OfType<string>());

Or just do it in one line:

List<string> selectedFields = chkDFMFieldList.CheckedItems.OfType<string>().ToList();
Chromonema answered 23/1, 2009 at 2:0 Comment(2)
Is there a way to know the type of the ItemCollection? So the method works with any ItemCollection without knowing the typeGogol
"OfType<string>()" -- I learned something new today! Thanks Matt!Champagne
V
17

This is not exactly the answer to your requirement, but posting a more general answer. You could do it in a variety of ways:

1)

T[] items = new T[lb.Items.Count];
lb.Items.CopyTo(items, 0);
var lst = new List<T>(items);

2) looping and adding using foreach as you mentioned.

3) using Linq

var lst = lb.Items.Cast<T>().ToList();

4) or

var lst = lb.Items.OfType<T>().ToList();

When I did some performance testing like below, I found copying to array method the fastest while the Linq methods slower. Of course in real world scenarios these wouldnt matter. I prefer the 3rd method (Linq) for readability.

DateTime d = DateTime.Now;
for (int i = 0; i < 10000; i++)
{
    Action();
}
MessageBox.Show((DateTime.Now - d).TotalMilliseconds.ToString());

For an iteration of 10000 times run multiple times with about 300 items in list box,

1) ~100ms

2) ~150ms

3) ~250ms

4) ~260ms

Valeric answered 9/7, 2012 at 18:18 Comment(1)
Digging in the vast archive of StackOverflow... @nawfal, the advantage of solution 4) is that if you have different items in your collection (e.g. menu with MenuItems and Separators) OfType<T> will simply choose only <T> items from the collection, while 3) will throw InvalidCastException.Hypogenous
C
1

If you don't have access to LINQ then there isn't a more elegant way since you're performing a second operation on the list items (calling ToString()) in addition to populating the selectedFields collection.

Cammack answered 23/1, 2009 at 2:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.