2011-06-22 8 views
0

私がXAttribute値からGUIDを取得するためのLINQを使用しようとしています...戻りGUIDが属性値、またはGuid.EmptyはのXElement/XAttributeは

XDocument __xld = XDocument.Parse(
"<Form sGuid='f6b34eeb-935f-4832-9ddc-029fdcf2240e' 
sCurrentName='MyForm' />"); 

string sFormName = "MyForm"; 

Guid guidForm = new Guid(

    __xld.Descendants("Form") 
    .FirstOrDefault(xle => xle.Attribute("sCurrentName").Value == sFormName) 
    .Attribute("sGuid").Value 

); 

事があり、私は希望を見つけていない場合XAttributeが見つからない場合、またはXElementが見つからない場合は、Guid.Emptyを返すようにしてください(または何かが間違っています)...

このコンセプトを1行で実行できますか、最初に一致するsCurrentNameを持つXElementが見つかったかどうかを確認し、クエリが何も返さない場合はGuid.Emptyを返します。


UPDATE Miroprocessorへ

おかげで、私は次のよう...

Guid guidForm = new Guid(

    (from xle in __xld.Descendants("Form") 
    where xle.Attribute("sCurrentName") != null && xle.Attribute("sCurrentName").Value == sFormName 
    select xle.Attribute("sGuid").Value).DefaultIfEmpty(Guid.Empty.ToString()).FirstOrDefault() 

); 

になってしまったBUTている(!)私は場合Guid.Empty.ToStringは()を避けることができると思いますクエリ内にGuidを作成することができます(可能な場合)。

答えて

1

はそうあなたがguidForm.Value

を書いたり、

Guid guidForm =new Guid(from xle in __xld.Descendants("Form") 
       where xle.Attribute("sCurrentName").Value == sFormName 
       select xle.Attribute("sGuid").Value==null?Guid.Empty:xle.Attribute("sGuid").Value).Single()); 

ことをしようとした結果にアクセスするために

var guidForm =(from xle in __xld.Descendants("Form") 
       where xle.Attribute("sCurrentName").Value == sFormName 
       select new {Value = xle.Attribute("sGuid").Value==null?Guid.Empty:new Guid(xle.Attribute("sGuid").Value)}).Single(); 

を試みるが、私はそれが正しく

+0

おかげで動作するかわからないけど、私はどこかでDefaultIfEmpty(Guid.Empty)を使用できるかもしれないと思っていたが、私はheaを得ることができないそれがどのように書かれようとしていたのか! – user597118

+0

私の回答を編集する –

+0

私はあなたの例を使用して私の質問を更新しました...ありがとう – user597118

関連する問題