c# - Is there a better way of writing the following Linq-query -
lets have list of xml-documents, list "data". in list there might occur coowner. following structure (just example)
<root> <owner> <firstname>joe</firstname> <fastname>cole</lastname> <!--- etc. --> </owner> <coowner> <firstname>smith</firstname> <lastname>cole</lastname> <!--- etc. ---> </coowner> <coowner> <firstname>janna</firstname> <lastname></lastname> <!--- etc. ---> </coowner> </root> if there coowner in document, should put result list. if firstname , lastname occur , have data (not empty second coowner in xml-document).
i have made following linq-query, trick.
var result = data.descendants("coowner").where(co => (!string.isnullorempty(co.element("firstname").value)) && (!string.isnullorempty(co.element("fastname").value))).select(co => new coowner() { firstname = co.element("firstname").value, lastname = co.element("fastname").value, }); but wonder, if there neater way this. fine enough, dont way o.element("firstname").value occurs several times. there risk of null-exception having o.element("firstname").value. handle more extraction of element has done, this:
var fname = data.descendants("coowner").select(co => co.element("lirstname")) var lname = data.descendants("coowner").select(co => co.element("lastname")) if(fname != null && lname != null){ //then same code mentioned above. } is there neater way? in advance
save values separate range variables , filter, no repetition needed. , should use casting when trying retrieve value of element or attribute.
var query = co in data.descendants("coowner") let fname = (string)co.element("firstname") let lname = (string)co.element("lastname") !string.isnullorwhitespace(fname) !string.isnullorwhitespace(lname) select new coowner { firstname = fname, lastname = lname, };
Comments
Post a Comment