按对象类型从列表中选择

Pav*_*vel 0 c#

我项目的结构:

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

class Page
{
    public List<Attachment> attachments;
                ...
}
Run Code Online (Sandbox Code Playgroud)

我收到服务器的页面:

List<Page> pages = ...load pages from server;
Run Code Online (Sandbox Code Playgroud)

我需要从这个列表页面中获取附件中只有类型为Photo的对象.

我该怎么做?

Tim*_*ter 6

你可以使用OfType:

var photos = attachments.OfType<Photo>();
Run Code Online (Sandbox Code Playgroud)

如果您希望所有网页只包含照片附件:

var pagesWithPhotosOnly = pages.Where(p => p.attachments.All(pa => pa is Photo));
Run Code Online (Sandbox Code Playgroud)


And*_*i V 5

实现此目的的一种方法是迭代列表并检查其类型Attachment.

var photos = attachments.Where(a => a is Photo);
Run Code Online (Sandbox Code Playgroud)

正如评论和@TimSchmelter的回答中所指出的,另一种方法是直接使用OfType扩展方法,这种方法可以说比使用更具"表现力" Where.

  • "OfType"的另一个潜在好处,而不是上面的"Where",就是`OfType`返回类型为"as"的项目(不需要额外的转换). (2认同)