Cleaner way to convert collection into another type?
I have a control, RadT开发者_如何转开发abStrip, 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?
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.)
Have you tried - var oldTabs = Tabs.OfType<CormantRadTab>().ToList();
精彩评论