views:

1391

answers:

3

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.

+2  A: 

Try this (using 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();
Matt Hamilton
A: 

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.

Ken Browning
A: 

Thanks guys, this is what I am looking for.

I want to give you all points but I suppose I should give it to Mr Hamilton.

Alex
You can still vote the other guys up!
Matt Hamilton