我有一个LinqToXML表达式,我试图根据类似的属性选择不同的名称.代码工作得很好,我把它放在下面:
var q = xmlDoc.Element("AscentCaptureSetup").Element("FieldTypes")
.Descendants("FieldType")
.Select(c => new { width = c.Attribute("Width").Value,
script = c.Attribute("ScriptName").Value,
sqlType = c.Attribute("SqlType").Value,
enableValues = c.Attribute("EnableValues").Value,
scale = c.Attribute("Scale").Value,
forceMatch = c.Attribute("ForceMatch").Value,
forceMatchCaseSensitive = c.Attribute("ForceMatchCaseSensitive").Value,
sortAlphabetically = c.Attribute("SortAlphabetically").Value,
})
.Distinct();
Run Code Online (Sandbox Code Playgroud)
问题出现了,因为不是所有属性都是必需的,如果省略其中一个属性,例如sortAlphabetically,我得到一个Object not Referenced错误.有道理,但有一种方法可以改变查询,只有在属性实际存在时才使用新值?(从而绕过任何空指针错误)
除了使用的Value财产(这将炸毁的空引用),简单地把XAttribute字符串-你要么得到的值,或空引用如果XAttribute引用为null.(XElement以相同的方式工作,这适用于所有转换为可空类型.)
所以你有:
.Select(c => new {
width = (string) c.Attribute("Width"),
script = (string) c.Attribute("ScriptName"),
sqlType = (string) c.Attribute("SqlType"),
enableValues = (string) c.Attribute("EnableValues"),
scale = (string) c.Attribute("Scale"),
forceMatch = (string) c.Attribute("ForceMatch"),
forceMatchCaseSensitive = (string) c.Attribute("ForceMatchCaseSensitive"),
sortAlphabetically = (string) c.Attribute("SortAlphabetically"),
})
Run Code Online (Sandbox Code Playgroud)
其中一些属性听起来像他们应该实际上被转换为int?或bool?,你要知道...
| 归档时间: |
|
| 查看次数: |
334 次 |
| 最近记录: |