2015-03-25 58 views
0

結構:選擇我的項目

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

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

我從服務器接收網頁:

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

我需要從這個列表頁面,其附件中只有對象,以得到與類型的照片。

我該怎麼辦?

+3

'.OfType ()' – crashmstr 2015-03-25 12:29:02

回答

6

您可以使用OfType

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

如果你想要,而不是隻用照片附件的所有頁面:

var pagesWithPhotosOnly = pages.Where(p => p.attachments.All(pa => pa is Photo)); 
+0

謝謝,這是我需要的 – Pavel 2015-03-25 12:44:55

5

實現此目的的一種方法是迭代列表並檢查Attachment的類型。

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

另一種方法,作爲評價和@ TimSchmelter的回答指出,是直接使用OfType擴展方法,這可以說是比使用Where更多的「表現」。

+2

另一個'OfType'而不是潛在的益處像上面那樣的'Where'就是'OfType'返回類型爲'as'的類型(不需要額外的轉換)。 – crashmstr 2015-03-25 12:33:32

+0

@crashmstr,點了。如果你需要在過濾後訪問'Photo'對象的成員,'OfType'就是要走的路。 – 2015-03-25 12:35:44