2011-07-08 31 views
1

我有一個ObservableCollection<Object>,它包含兩種不同類型的對象:DirectoryFile。這個集合必然是一個控件,有時候我想過濾掉File某些類型的過濾器對象ObservableCollection <Object>

我有以下的代碼,這是行不通的:

var files = (from File f in (from Directory d in selectedDirs 
          select d.Childs) 
      where f is File 
      select f); 

我得到這個錯誤:

Unable to cast object of type 'System.Collections.ObjectModel.ObservableCollection`1[System.Object]' to type 'CMBraga_FileExplorer.File'.

我怎樣才能得到我的價值觀?我知道他們是File s。

// this was ran without explicit conversion (just as an example) 

? myCollection 
Count = 5 
    [0]: {CMBraga_FileExplorer.File} 
    [1]: {CMBraga_FileExplorer.File} 
    [2]: {CMBraga_FileExplorer.File} 
    [3]: {CMBraga_FileExplorer.File} 
    [4]: {CMBraga_FileExplorer.File} 

回答

2

我懷疑你得到異常的原因是因爲你在聲明類型的查詢變量(即​​)的。通過這樣做,您試圖將對象轉換爲指定的類型。看起來您d.Childs中某些商品的類型爲ObservableCollection<Object>。那些顯然不是File對象,因此鑄造錯誤。使用Enumerable.OfType()擴展方法在這裏進行篩選。這正是它所做的。

var files = selectedDirs 
    .Cast<Directory>() // this cast might not even be necessary 
    .SelectMany(d => d.Childs) 
    .OfType<File>(); // filter selecting only File objects 
1

您可以使用LINQ表達式爲:

using System.Linq; 
// ... 
ObservableCollection<object> list; 
// ... 
IEnumerable<CMBraga_FileExplorer.File> castedList = list.Cast<CMBraga_FileExplorer.File>(); 
+0

地獄是的工作!非常感謝你們! –