Miguel Moura
Miguel Moura

Reputation: 39374

Use anonymous type in generic class

I have the following class with an Add mapper

public class OrderMapper<T> {
  public OrderMapper<T> Add<TKey>(Expression<Func<T, TKey>> expression, String name) {
  }
}

which I use as follows:

OrderMapper<Post> mapper = new OrderMapper<Post>().Add(x => x.Created, "created");

The problem is that sometimes I have the following:

posts.SelectMany(x => x.Category, (Post, Category) => new { Post, Category });

Which returns a list of anonymous types:

var objects = new { Post post, Category category }

I am not sure how to create an OrderMapper of this type ...

I think maybe I need to change my class method to an extension like:

OrderMapper mapper = objects.Add(...).Add(...)

Could someone tell me the best way to do this?

Upvotes: 1

Views: 249

Answers (1)

Xiaoy312
Xiaoy312

Reputation: 14477

You can use a Create method for the OrderMapper class :

public class OrderMapper
{
    public static OrderMapper<T> CreateMapperFor<T>(IEnumerable<T> typeProvider)
    {
        return new OrderMapper<T>();
    }
}

And, use it as such :

var objects = Enumerable.Repeat(new { /* ... */ }, 1);
var mapper = OrderMapper.CreateMapperFor(objects)
    .Add(/*...*/)
    .Add(/*...*/);

Upvotes: 3

Related Questions