Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleaner way to convert collection into another type?

Tags:

c#

linq

I have a control, RadTabStrip, which contains: public RadTabCollection Tabs { get; }. The class RadTabCollection 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 a list of CormantRadTab with the RadTabCollection. Currently, I have this implemented:

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

I really feel like I should be able to do something such as:

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

but this does not match the overload signature New List is expecting. If I try and cast AsEnumerable CormantRadTab I receive other errors.

What's the proper way to do this?

like image 878
Sean Anderson Avatar asked Dec 21 '22 07:12

Sean Anderson


2 Answers

You can use Enumerable.Cast<>:

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

Or if there are some non-CormantRadTab elements and you only want to select the CormantRadTab ones, 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, whichever you prefer.)

like image 58
Jon Skeet Avatar answered Dec 24 '22 02:12

Jon Skeet


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

like image 27
Kevin Stricker Avatar answered Dec 24 '22 00:12

Kevin Stricker