how to check an attribute value when that attribute may or may not exist
-
10. května 2012 17:22
My LINQ statement looks like
My problem is that neither file.Attribute(Global.xnToKeep). nor file.Attribute(Global.xnProtected) are guaranteed to exist in file. So, I need to test their existence before testing what their value is. How do I do that in a LINQ statement?List<XElement> filteredset
= (from file in matchingsets.Elements<XElement>(Global.xnFile)
where (((string)file.Attribute(Global.xnToKeep).Value != "*") && ((string)file.Attribute(Global.xnProtected).Value != "*") &
& File.Exists(file.Attribute(Global.xnPath).Value))
select file).ToList<XElement>();
Všechny reakce
-
11. května 2012 4:25
Try this,
List<XElement> filteredset
= (from file in matchingsets.Elements<XElement>(Global.xnFile)
where (
(file.Attribute(Global.xnToKeep) != null &&(string)file.Attribute(Global.xnToKeep).Value != "*")
&& (file.Attribute(Global.xnProtected) != null &&(string)file.Attribute(Global.xnProtected).Value != "*")
&& File.Exists(file.Attribute(Global.xnPath).Value)
)select file).ToList<XElement>();
Best Regards Sanjay Pant [Metadesign Solutions]
- Upravený Sanjay Pant 11. května 2012 4:25
- Navržen jako odpověď Link.fr 12. května 2012 18:15
-
11. května 2012 9:26
The LINQ to XML API supports your use case easily, simply do
List<XElement> filteredset = (from file in matchingsets.Elements<XElement>(Global.xnFile) where (string)file.Attribute(Global.xnToKeep) != "*" && (string)file.Attribute(Global.xnProtected) != "*" && File.Exists(file.Attribute(Global.xnPath).Value)) select file).ToList<XElement>();
instead of what you have. If the attribute of a certain name (say "foo") does not exist then
file.Attribute("foo")
is null and the conversion operators ensure that
(string)file.Attribute("foo")
is also null. And the comparison
null != "*"
is possible whereas in your case with
file.Attribute("foo").Value
you get a NullReferenceException if the attribute does not exist.
MVP Data Platform Development My blog
- Navržen jako odpověď Link.fr 12. května 2012 18:15