c# - What magic is this? -
i came across post infamous jon skeet regarding utilize of linq xml. particular snippet of code caught eye:
// customers list<customer> xelement customerselement = new xelement("customers", customers.select(c => new xelement("customer", //this line "magic" new xattribute("name", c.name), new xattribute("lastseen", c.lastorder) new xelement("address", new xattribute("town", c.town), new xattribute("firstline", c.address1), // etc ));
i decided test myself in application had foreach loop set so:
foreach (var kvp in m_jobs) { //m_jobs dictionary<string,job> m_xmldoc.root.element("sched_table").add( kvp.value.generatexmlnode()) ); }
i modifed to:
m_xmldoc.root.element("sched_table").add( m_jobs.select(job => job.value.generatexmlnode()) };
where generatexmlnode() method genrates appropriate xml mark-up particular job item. wasn't sure happen lo , behold worked foreach loop did. don't quite understand why?! also, considered "abuse" or "feature" of linq?
edit clarity: know .select homecoming ienumerable containing asked i'm not expressly enumerating it. understand how .add works because accepts variable number of arguments again, don't expressly enumerate pass arguments. so... how still work?
the xelement.add
method under hood:
public void add(object content) { if (content ienumerable) { foreach (object kid in (ienumerable)content) add(child); } else { //process individual element } }
so while it's not clear public interface of add
, can pass either sequence of items, or single item, , determine @ runtime , deed accordingly.
c# xml linq
No comments:
Post a Comment