Richthofen
Richthofen

Reputation: 2086

Use LINQ to transform single object into IEnumerable via Properties/reflection?

I have a simple object like such:

public class Foo {
    public int One { get; set; }
    public int Two { get; set; }
    ....
    public int Eleven { get; set; }
} 

Given an IEnumerable, what I want is a LINQ method to transform as such:

myFooEnumerable.Select(n => transformMagicGoesHere);

Where my return object looks like this:

public class Bar {
    public string DurationDescription {get;set;} //Value would be "One" or "Two" or ...
    public int Value {get;set;} //Holds value in the property One or Two or ...
}

So for every item N in myFooEnumerable in the example above I'd get 11(N) items in my resultant select statement.

Upvotes: 2

Views: 381

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062905

This should do it:

var bars = myFooEnumerable.SelectMany(
    x => x.GetType().GetProperties().Select(p => new Bar {
        DurationDescription = p.Name,
        Value = (int)p.GetValue(x)
    }));

Not a great thing to be doing in the first place, IMO, but it will at least work.

Upvotes: 2

Related Questions