Casting an Item Collection from a listbox to a generic list

Alex picture Alex · Jan 23, 2009 · Viewed 33.9k times · Source

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.

Answer

Matt Hamilton picture Matt Hamilton · Jan 23, 2009

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();