first_page the funky knowledge base
personal notes from way, _way_ back and maybe today

LINQ to XML: “XML to IEnumerable<T>”; Andrew Hare; Using a Generic Method with an Interface Constraint

Given the following types:

public interface IFruit { String name { get; set; } Int32 id { get; set; } }

public class Fruit : IFruit { public String name { get; set; } public Int32 id { get; set; } }

I think that you could do something like this:

static IEnumerable&lt;T&gt; GetSomeFruit&lt;T&gt;(String xml)
    where T : IFruit, new()
{
    return XElement.Parse(xml)
            .Elements(&quot;fruit&quot;)
            .Select(f =&gt; new T {
                    name = f.Element(&quot;name&quot;).Value,
                    id = Int32.Parse(f.Element(&quot;id&quot;).Value)
            });
}

Which you would call like this:

IEnumerable<Fruit> fruit = GetSomeFruit<Fruit>(yourXml);

[http://stackoverflow.com/questions/1460567/xml-to-ienumerablet]

mod date: 2010-03-19T04:21:12.000Z