I have WPF TreeViewItems and I defined a custom object class for the Tag e.g. CustomTag with properties such as a Type, Name, Description.
I need to get all Items where the tag.Type = “test” so I defined the following Linq query:
if (!myNode.Items.Cast<TreeViewItem>().Any(item => item.Tag is CustomTag &&
(CustomTag)item.Tag.Type = "test")) { ...
Unfortunately Visual Studio doesn’t like it and I can’t work out a proper way to do it
1
I think it complains about this part (CustomTag)item.Tag.Type = "test"
– because it tried to read Tag
from object
and because =
is not a comparison.
You would need tell explicitly to do parsing first: ((CustomTag)item.Tag).Type == "test"
, but there is much nicer syntax you can use: pattern matching:
if (!myNode.Items
.Cast<TreeViewItem>()
.Any(item => item.Tag is CustomTag customTag && customTag.Type == "test"))
Or
if (!myNode.Items
.Cast<TreeViewItem>()
.Any(item => item.Tag is CustomTag { Type: "test" }))
4