petr346
petr346

Reputation: 25

Convert IEnumerable<T> to collection of dynamically generated objects

Recently I asked a more general question about getting properties of model through foreign key. Now I moved a bit further but still have no idea how transform objects on the fly.

What I've got is an IEnumerable collection which I get through repository

regionRaw = unitOfWork.RegionRepository.Get(
    keyOrder: q => q.OrderBy(d => d.RegionID),
    filter: p => p.FullName.Contains(lastname) || p.ShortName.Contains(lastname),
    orderBy: jtSorting,
    includeProperties: "District, ISO31662, GOST767Region");

Further I am going to export data from this collection to Excel. So I need a select statement that gets all the fields I need.

dt = regionRaw
    .Select(x => new
    {
        ISO = x.ISO31662.GOSTName,
        DistrictName = x.District.ShortName
    })

I do not want to enumerate all the fields I need like on the top.

I am able to make a method that recognizes which of the fields have simple values and which have objects referenced through foreign key. And then that method will return a list of properties.

Now I need some way to write something like a foreach inside select. I see something like this:

dt = regionRaw
     .Select(x => new
     {
         foreach (prop in propList)
         {
             prop.PropertyName = x.GetType()
                 .GetProperty(prop.TableName)
                 .GetValue(x, null).GetType()
                 .GetProperty(prop.PropertyName)
                 .GetValue(
                     x.GetType().GetProperty(prop.TableName).GetValue(x, null),
                     null);
         }
     }

Where propList is a collection of properties that I get before.

I do totally realize that upper code is more a pseudo-code but I have no idea how to realize this in .NET.

So if you can suggest some solution for this task I will be very grateful. Or maybe you could explain that all this is a bad idea and shouldn't be realized.

Upvotes: 2

Views: 1339

Answers (1)

Jonas Jämtberg
Jonas Jämtberg

Reputation: 571

You wont be able to create an anonymous type with dynamic properties as anon types are created during compile and your properties are created during execution.
But why do you need strongly typed properties if you're not going to code against them, as you wont know them until someone executes the query?

Expando object may be of use to you?
http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject.aspx

Upvotes: 2

Related Questions