views:

753

answers:

3

My last question was about getting the string representation of an object serialized to XML. One of the responders wrote an extension method to encapsulate the serialization process.

My question now is how can I use an Extension Method to return an array of strings, when passed an IEnumerable<T> object, where each string in the array would be an individually serialized element of the IEnumerable<T>.

Thanks in advance!

+5  A: 

using the code example from your link, you could add another method like this or convert them into array using ToArray() method.

public static class XmlTools
{
  public static IEnumerable<string> ToXmlString<T>(this IEnumerable<T> inputs)
  {
     return inputs.Select(pArg => pArg.ToXmlString());
  }
}
Vasu Balakrishnan
Possibly of interest: the research language Cω (where some of the ideas of Linq were first prototyped) defined your example method automatically. `IEnumerable<T>` would effectively have methods with the same names as the methods of `T`, except the return type `R` would become `IEnumerable<R>`. It was like `Select` being built into the language in a very succinct way.
Daniel Earwicker
+2  A: 

I would write my extension method to produce a new IEnumerable rather than an array:

public static IEnumerable<string> XmlSerializeAll<T>(this IEnumerable<T> input)
{
    foreach (T item in input)
    {
        yield return item.ToXmlString();
    }
}

You can get the array you want easily by using

var myArray = myEnumerable.XmlSerializeAll().ToArray();

This way, you add some flexibility. It's possible to produce a List instead, or use infinitely long enumerations if you like :)

Thorarin
darn you beat me
Matthew Whited
Any excuse to produce some code with yield :)
Thorarin
+5  A: 

To answer your next several questions...

new XElement("people", myPeople.ToXElements());


public static class XmlTools
{
    public static XElement ToXElement<T>(this T input)
    {
        return XElement.Parse(input.ToXmlString());
    }
    public static IEnumerable<XElement> ToXElements<T>(this IEnumerable<T> input)
    {
        foreach (var item in input)
            yield return input.ToXElement();
    }
    public static IEnumerable<string> ToXmlString<T>(this IEnumerable<T> input)
    {
        foreach (var item in input)
            yield return item.ToXmlString();
    }
    public static string ToXmlString<T>(this T input)
    {
        using (var writer = new StringWriter())
        {
            input.ToXml(writer);
            return writer.ToString();
        }
    }
    public static void ToXml<T>(this T objectToSerialize, Stream stream)
    {
        new XmlSerializer(typeof(T)).Serialize(stream, objectToSerialize);
    }

    public static void ToXml<T>(this T objectToSerialize, StringWriter writer)
    {
        new XmlSerializer(typeof(T)).Serialize(writer, objectToSerialize);
    }
}
Matthew Whited