XDocument document = XDocument.load("foo.xml");
var elements = from e in document.Descendants("bar")
where e.Attribute("hoge").Value == "foobar"
select e;
すると,適当な属性が無い場合null参照で怒られる.で、こう書き換えていた.
XDocument document = XDocument.load("foo.xml");
var elements = from e in document.Descendants("bar")
where e.Attribute("hoge") != null && e.Attribute("hoge").Value == "foobar"
select e;
でもこれ冗長だなぁ、と思っていたわけで.調べてみると、文字列へのキャストをした方が良い感じ.
XDocument document = XDocument.load("foo.xml");
var elements = from e in document.Descendants("bar")
let hoge = (string)e.Attribute("hoge")
where hoge != null && hoge == "foobar"
select e;
で、ふと思ったのが、文字列型の変数がnullの場合,比較したら落ちるのかな,と.
string a = null;
string b = "hello";
if(a != b){
Console.WriteLine("not same");
}
ちゃんと比較できるっぽいので,こうすればいちいちnullチェックいらないんじゃね,ということで
XDocument document = XDocument.load("foo.xml");
var elements = from e in document.Descendants("bar")
let hoge = (string)e.Attribute("hoge")
where hoge == "foobar"
select e;
と,ここにたどり着いた.