Usher
Usher

Reputation: 2146

How to convert an object collection to an array of Enum

I seem to be stuck trying to convert a collection of ListBox items to Enum.

Here is my code

 ChannelCodeType[] ChannelCodes = lbSearch.SelectedItems;


public enum ChannelCodeType {

        /// <remarks/>
        XYZ1,

        /// <remarks/>
        XYZ1_KIDS,

        /// <remarks/>
        XYZ1_PRIME,

        /// <remarks/>
        XYZ13,

        /// <remarks/>
        XYZ14,
    }

I am trying to pass the values (selecteditems) back to the ChannelCodes

Upvotes: 0

Views: 426

Answers (1)

Grant Winney
Grant Winney

Reputation: 66509

The SelectedItems property is most likely a collection of type Object.

Try casting the collection back to the original type:

ChannelCodeType[] ChannelCodes
    = lbSearch.SelectedItems.Cast<ChannelCodeType>().ToArray();

I'm assuming lbSearch is a ListBox and that it's been filled with ChannelCodeType values.


If Baldrick is right, and you've got string representations of the ChannelCodeType enum values, then you may need to modify the code to parse the strings back to the original enum:

ChannelCodeType[] ChannelCodes
  = lbSearch.SelectedItems
            .Cast<string>()
            .Select(c => (ChannelCodeType)Enum.Parse(typeof(ChannelCodeType), c))
            .ToArray();

Upvotes: 4

Related Questions