0

Structure of my project:

class Attachment { ... }
class Photo : Attachment { ... }
class Document : Attachment { ... }

class Page
{
    public List<Attachment> attachments;
                ...
}

I receive pages from the server:

List<Page> pages = ...load pages from server;

I need to get from this list pages which in the Attachments have only objects with type Photo.

How can I do it?

0

2 Answers 2

6

You can use OfType:

var photos = attachments.OfType<Photo>();

If you instead want all pages with only photo-attachments:

var pagesWithPhotosOnly = pages.Where(p => p.attachments.All(pa => pa is Photo));
Sign up to request clarification or add additional context in comments.

Comments

5

One way of achieving this is iterating the list and checking the type of the Attachment.

var photos = attachments.Where(a => a is Photo);

Another method, as pointed in the comments and @TimSchmelter's answer, is to directly use the OfType extension method, which is arguably more "expressive" than using Where.

2 Comments

Another potential benefit of OfType instead of a Where like above is that OfType returns the items that are the type as the type (no additional casting required).
@crashmstr, point taken. If you'd need to access the member of the Photo objects after the filtering, OfType would be the way to go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.