Convert CollectionBase to List or data type usable with Linq

我的未来我决定 提交于 2019-12-04 08:19:07

问题


I am using Aspose cells to manipulate Excel spreadsheets. One of the types in the API is a collection of Pictures in the spreadsheet, which derives from CollectionBase:

see this link: http://www.aspose.com/documentation/.net-components/aspose.cells-for-.net/aspose.cells.pictures.html

I want to convert this type to something that allows me to use Linq expressions

What are the options for this?

I guess I could iterate over it and manually add it to a new List<Picture> But is there a better way to do this?

I have read this question Adding IEnumerable<T> to class derived from CollectionBase

But I obviously don't have control over the class that implements CollectionBace as it is a third party product


回答1:


Just use the Enumerable.Cast<T>() extension method on the non-generic IEnumerable interface, which you can do implicitly in a query expression:

var query = from Picture picture in pictures
            where ...
            select ...;

or explicitly, for instance if you want to use dot notation:

var query = pictures.Cast<Picture>()
                    .Where(...)
                    .Select(...);

An alternative to Cast<T>() is OfType<T>() - which basically ignores any elements which aren't of the right type. In this case I think Cast<T>() is more appropriate though.

If you want to convert the whole collection to a List<T> for whatever reason, that's easy too:

List<Picture> list = pictures.Cast<Picture>().ToList();


来源:https://stackoverflow.com/questions/1571425/convert-collectionbase-to-list-or-data-type-usable-with-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!