2013-07-01 20 views
1

編輯:下面的代碼工程! (我評論,建立,後來未註釋,它的工作)。Linq可觀察到的收藏投射錯誤

我有一個ObservableCollectionListBox。我只想根據顯示名稱選擇其中一些項目,因爲我不知道項目值。然而,我得到一個轉換錯誤(IEnumerable到ObservableCollection)。

ObservableCollection<ListBoxItem> unselectedcollection 
    = new ObservableCollection<ListBoxItem> 
     (dt.AsEnumerable() 
      .Select(i => new ListBoxItem(i[ColumnNames.LISTNAMECOL].ToString(), 
             i[ColumnNames.LISTVALUECOL].ToString()))); 

ObservableCollection<ListBoxItem> selectedcollection 
    = new ObservableCollection<ListBoxItem> 
     (from item in unselectedcollection.AsEnumerable() 
     where (item.Name == "firstName" 
       || item.Name == "secondName" 
       || item.Name == "thirdName") 
     select item); 

我已經試過我能想到的各種鑄造選項。我錯過了什麼?

+0

也包括你的第一個集合('unselectedcollection'),這可能是問題的根源。 –

+0

什麼是未選擇收藏的類型? – PoweredByOrange

+0

我已將它添加到原始問題 – SeeMoreGain

回答

0

當處理集合並將Linq結果傳遞給它們時遇到的一個常見問題是集合未枚舉,並且通過調用ToList來枚舉集合通常會修復問題。我會給它一個去看看是否有幫助。

ObservableCollection<ListBoxItem> selectedcollection 
    = new ObservableCollection<ListBoxItem>(
     unselectedcollection.AsEnumerable() 
          .Where(item => item.Name == "firstName" 
             || item.Name == "secondName" 
             || item.Name == "thirdName") 
          .ToList()); 
0

我無法解釋如何或爲什麼,但我註釋了本節,填充空白列表以保持測試。我剛回來,並取消註釋它給出確切的錯誤信息(按照@nakiya的要求),並重建...

...它的工作。

我再次不知道如何或爲什麼,但至少我可以繼續前進。