I need "Enumerator adaptor", or something like this

C

cctv.star

I've got a class that encapsulates certain logs as an XmlDocument. I
need to implement 2 properties (Errors and Warnings), which should be
enumerable by foreach statement, and which should be implemented by
reading this XML document. I guess I need some kind of "enumerator
adaptor" in order to convert XmlNode objects into my "Message"
objects, and I need to feed this adaptor with the output of
XmlDocument.SelectNodes call. Something like this:

<code>

class CheckResults {

public MessageCollection Errors {
get { return new SomeNiftyEnumAdaptor(
_doc.SelectNodes("/some/message[type='error']"),
delegate () { some conversion code here} ); };
}

public MessageCollection Warnings {
get { return new SomeNiftyEnumAdaptor(
_doc.SelectNodes("/some/message[type='warning']"),
delegate () { some conversion code here} ); };
}

private XmlDocument _doc;
}

// client code:

foreach(Message msg in results.Errors) {
}

</code>

The trouble is, the code that I've written so far is quite a
screenful. Which is strange, considering that the only specific stuff
here is this conversion function, which constructs my custom Message
type from XmlNode - everything else is just boilerplate code.

So, what's the proper wat to do this in C#?
 
J

Jon Skeet [C# MVP]

I've got a class that encapsulates certain logs as an XmlDocument. I
need to implement 2 properties (Errors and Warnings), which should be
enumerable by foreach statement, and which should be implemented by
reading this XML document. I guess I need some kind of "enumerator
adaptor" in order to convert XmlNode objects into my "Message"
objects, and I need to feed this adaptor with the output of
XmlDocument.SelectNodes call. Something like this:

The trouble is, the code that I've written so far is quite a
screenful. Which is strange, considering that the only specific stuff
here is this conversion function, which constructs my custom Message
type from XmlNode - everything else is just boilerplate code.

So, what's the proper wat to do this in C#?

Almost certainly with iterator blocks. However, it's hard to know
exactly what you want to do with the nodes you've selected. The code
would be *something* like:

public IEnumerable<Message> Warnings
{
get
{
XmlNodeList list = _doc.SelectNodes
("/some/message[type='warning']");

foreach (XmlNode node in list)
{
// Conversion goes here...
yield return new Message(node);
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top