A cleaner way to convert collections to a different type?

I have a RadTabStrip control that contains: public RadTabCollection Tabs { get; } public RadTabCollection Tabs { get; } . The RadTabCollection class inherits from: public class RadTabCollection : ControlItemCollection, IEnumerable<RadTab>, IEnumerable

Now I have a list of CormantRadTab. This class inherits: public class CormantRadTab : RadTab, ICormantControl<RadTabSetting>

My goal is to populate the CormantRadTab list with RadTabCollection. Currently this is implemented:

 List<CormantRadTab> oldTabs = new List<CormantRadTab>(Tabs.Count); foreach( CormantRadTab tab in Tabs) { oldTabs.Add(tab); } 

It really seems to me that I can do something like:

 List<CormantRadTab> oldTabs = new List<CormantRadTab>(Tabs.AsEnumerable<RadTab>()); 

but this does not match the overload signature expected by the new list. If I try to use AsEnumerable CormantRadTab, I get other errors.

What is the right way to do this?

+4
source share
2 answers

You can use Enumerable.Cast<> :

 var oldTabs = Tabs.Cast<CormantRadTab>().ToList(); 

Or, if there are some elements other than CormantRadTab, and you only want to select CormantRadTab, use OfType<> :

 var oldTabs = Tabs.OfType<CormantRadTab>().ToList(); 

(In both cases, the result will be of type List<CormantRadTab> - use explicit typing or implicit typing, depending on what you prefer.)

+8
source

Have you tried - var oldTabs = Tabs.OfType<CormantRadTab>().ToList();

+3
source

All Articles