2012-10-31 66 views
1

我與一個函數執行操作(我想用LINQ),並返回一個對象像這樣的集合庫工作:從LINQ查詢檢索IDS導致

System.Collections.Generic.IEnumerable<ColorInformation> 

這個「ColorInformation」是看起來像這樣的一個類:

public class ColorInformation 
{ 
    private readonly System.Drawing.Color color; 
    private readonly string rowTitle; 
    private readonly System.Collections.Generic.List<int> ids; 

    public ColorInformation(System.Drawing.Color color, string rowTitle, 
     System.Collections.Generic.List<int> ids) 
    { 
     this.color = color; 
     this.rowTitle = rowTitle; 
     this.ids = ids; 
    } 

    public string RowTitle 
    { 
     get { return rowTitle; } 
    } 

    public System.Drawing.Color Color 
    { 
     get { return color; } 
    } 

    public System.Collections.Generic.List<int> Ids 
    { 
     get { return ids; } 
    } 
} 

我有興趣檢索返回的集合中的所有對象的所有id。我試過這個:

var myids = from ids in theCollectionReturned select ids.Ids; 

這給了我一個與ID列表的集合。我真正想要的只是一個包含所有整數ID的列表。所以,必須在某個地方進行演員或某個轉換,而我不知道該怎麼做。任何幫助,提示,閱讀,代碼,例子將不勝感激。 謝謝!

回答

8

我真正想要的只是一個包含所有整數ID的列表。

這聽起來像你想:

var ids = theCollectionReturned.SelectMany(info => info.Ids); 
+0

只是出於興趣喬恩,你更喜歡在查詢語法,流利的擴展方法的語法?我更喜歡流利的語法我自己...我覺得它更簡潔 –

+2

@DanFox:其中查詢表達式語法*是*簡要,我會用它。但我寧願使用這個比'從info.Ids選擇id'中的idCollectionReturned中的信息'這是遠遠cruftier。我發現流利的語法對於單個呼叫通常更簡單,例如只是一個選擇,只是一個地方,或只是一個SelectMany。查詢表達式通過連接,組等方式進入自己的行列。最好是對兩者都適應,並且對任何給定的查詢使用最適合的查詢表達式。 –

+0

哇!那很快!感謝喬恩,那正是我需要的。 –