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

Attribute().ValueXLinq では、正確なエラーが発生するため、通常は直接使用しません。代わりに、あなたはそれをキャストします。nullnull が返された場合、キャストの結果Attribute()は null になるため、例外はありません。

したがって、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 に答える