过滤对象 ObservableCollection
我有一个 ObservableCollection
我有以下代码,但不起作用:
var files = (from File f in (from Directory d in selectedDirs
select d.Childs)
where f is File
select f);
我收到此错误:
无法转换类型的对象 'System.Collections.ObjectModel.ObservableCollection`1[System.Object]' 输入“CMBraga_FileExplorer.File”。
我怎样才能得到我的价值观?我知道它们是File
。
// 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 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 File
s.
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 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}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我怀疑您收到异常的原因是因为您声明了查询变量的类型(即
from File f in ...
)。通过这样做,您正在尝试将对象转换为指定的类型。看起来d.Childs
中某些项目的类型是ObservableCollection
使用
Enumerable.OfType()
扩展这里的方法进行过滤。这正是它的用途。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.Childs
areObservableCollection<Object>
. Those are clearly notFile
objects hence the cast error.Use the
Enumerable.OfType()
extension method here to do the filtering. This is exactly what it was made for.您可以使用 Linq 表达式:
You can use Linq expression for that: