我项目的结构:
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的对象.
我该怎么做?
你可以使用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)
实现此目的的一种方法是迭代列表并检查其类型Attachment.
var photos = attachments.Where(a => a is Photo);
Run Code Online (Sandbox Code Playgroud)
正如评论和@TimSchmelter的回答中所指出的,另一种方法是直接使用OfType扩展方法,这种方法可以说比使用更具"表现力" Where.
| 归档时间: |
|
| 查看次数: |
63 次 |
| 最近记录: |