Using LINQ to map dynamically (or construct projections)

Posted by CodeGrue on Stack Overflow See other posts from Stack Overflow or by CodeGrue
Published on 2010-05-28T12:01:25Z Indexed on 2010/05/28 12:01 UTC
Read the original article Hit count: 255

Filed under:
|
|

I know I can map two object types with LINQ using a projection as so:

var destModel = from m in sourceModel
               select new DestModelType {A = m.A, C = m.C, E = m.E}

where

class SourceModelType
{
    string A {get; set;}
    string B {get; set;}
    string C {get; set;}
    string D {get; set;}
    string E {get; set;}
}

class DestModelType
{
    string A {get; set;}
    string C {get; set;}
    string E {get; set;}
}

But what if I want to make something like a generic to do this, where I don't know specifically the two types I am dealing with. So it would walk the "Dest" type and match with the matching "Source" types.. is this possible? Also, to achieve deferred execution, I would want it just to return an IQueryable.

For example:

public IQueryable<TDest> ProjectionMap<TSource, TDest>(IQueryable<TSource> sourceModel)
{
   // dynamically build the LINQ projection based on the properties in TDest

   // return the IQueryable containing the constructed projection
}

I know this is challenging, but I hope not impossible, because it will save me a bunch of explicit mapping work between models and viewmodels.

© Stack Overflow or respective owner

Related posts about LINQ

Related posts about mapping