I have a ObservableCollection<Object> that holds two different types of objects: Directory and File. This collection is bound to a control and at some time, I want to filter out the Files.
I have the following code, which is not working:
var files = (from File f in (from Directory d in selectedDirs
select d.Childs)
where f is File
select f);
I’m getting this error:
Unable to cast object of type
‘System.Collections.ObjectModel.ObservableCollection`1[System.Object]’
to type ‘CMBraga_FileExplorer.File’.
How can I get my values? I know they are Files.
// 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}
I suspect the reason you’re getting the exception is because you are declaring the types of your query variable (i.e.,
from File f in ...). By doing that, you are trying to cast the objects to the specified type. It would appear that your types of some of the items ind.ChildsareObservableCollection<Object>. Those are clearly notFileobjects hence the cast error.Use the
Enumerable.OfType()extension method here to do the filtering. This is exactly what it was made for.