1

考虑以下代码

IEnumerable<String> query = null;    
query = from x in xml.Descendants(xmlMasterContainerName).Descendants(xmlElementName)
                    let guid = x.Attribute("guid") ?? new XAttribute("guid", "-1")
                    where x.Attribute(xmlAttributeIdName).Value == xmlAttributeIdValue
                    select guid.Value;

尝试 query.ToList() 时出现“未设置对象引用”

当 'x.Attribute(xmlAttributeIdName).Value == xmlAttributeIdValue' 不存在时,这很可能是由 'select guid.Value' 引起的。

如何在选择之前检查现有值的 where 语句?谢谢

4

2 回答 2

3

在 Xlinq 中,您通常不Attribute().Value直接使用,因为您得到的确切错误。相反,你施放它。null如果返回 null,则强制转换将导致Attribute(),因此不会有异常。

因此,您可以将 where 子句更改为:

where ((string)x.Attribute(xmlAttributeIdName)) == xmlAttributeIdValue

以及您对此的选择:

select (string)guid

顺便说一句:我会这样写代码:

var query = xml.Descendants(xmlMasterContainerName)
               .Descendants(xmlElementName)
               .Where(x => ((string)x.Attribute(xmlAttributeIdName)) ==
                               xmlAttributeIdValue)
               .Select(x => (string)x.Attribute("guid") ?? "-1");
于 2013-02-07T12:05:13.680 回答
2

如果没有属性xmlAttributeIdName,您将获得访问属性的异常Value。改用强制转换(它将返回默认值)。你也不需要创建属性 - 你可以简单地返回值:

IEnumerable<String> query = null;    
query = from x in xml.Descendants(xmlMasterContainerName)
                     .Descendants(xmlElementName)
        where (string)x.Attribute(xmlAttributeIdName) == xmlAttributeIdValue
        select (string)x.Attribute("guid") ?? "-1";
于 2013-02-07T12:07:03.650 回答