开发者

Filter object ObservableCollection<Object> of some type

开发者 https://www.devze.com 2023-03-18 00:46 出处:网络
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 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开发者_StackOverflow 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 in d.Childs are ObservableCollection<Object>. Those are clearly not File objects hence the cast error.

Use the Enumerable.OfType() extension method here to do the filtering. This is exactly what it was made for.

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


You can use Linq expression for that:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号