2011-06-22 10 views
0

我試圖使用LINQ從XAttribute值獲得的Guid ...返回的Guid從XLINQ屬性值,或者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 

); 

的事情是,我會喜歡返回Guid.Empty,如果XAttribute丟失,或者如果找不到XElement,(或者出錯了!)...

我可以單線這個概念,還是我需要執行查詢首先查看是否找到了與匹配的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

嘗試

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(); 

所以要訪問結果你會寫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()); 

,但我不知道這將正常工作

+0

謝謝,但我想我可能能夠在某處使用DefaultIfEmpty(Guid.Empty),但我無法得到我的hea ð圍繞如何寫! – user597118

+0

我編輯我的答案檢查它 –

+0

我用你的例子和更新我的問題......謝謝 – user597118

相關問題