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