返回Guid来自XLinq属性值,如果未找到XElement / XAttribute则返回Guid.Empty

时间:2011-06-22 14:06:48

标签: c# xml linq linq-to-xml

我正在尝试使用Linq从XAttribute值获取Guid ...

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(或出现问题!)......

我可以使用这个概念,或者我是否需要首先执行查询以查看是否找到了具有匹配sCurrentName的XElement并且如果查询没有返回任何内容则返回Guid.Empty ...


更新

感谢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(如果可能的话),可以避免使用Guid.Empty.ToString()。

1 个答案:

答案 0 :(得分: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());

但我不确定能否正常使用

相关问题