I am trying to use Linq to get a Guid from an XAttribute value …
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
);
the thing is, i would like to return Guid.Empty if the XAttribute is missing, or if the XElement is not found, (or something goes wrong!) …
Can i one-liner this concept, or do i need to execute the query first to see if an XElement has been found with a matching sCurrentName and return Guid.Empty if the query returns nothing …
UPDATE
Thanks to Miroprocessor, i have ended up with the following …
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(!) i think the Guid.Empty.ToString() could be avoided if i could create the Guid inside the query (if that is possible).
try
so to access the result you will write
guidForm.Valueor try that
but I am not sure that will work correctly