Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use an Anonymous type on a method that accepts generic

Tags:

c#

c#-7.0

I have an OrderMapper class which I use as follows:

OrderMapper<Post> m = OrderMapper.For<Post>().Add("title", x => x.Title);

Where x is of type Post. The problem is when applying it to anonymous types.

var listOfAnonymousObjects = posts.SelectMany(x => x.PostsI18N, (Post, PostI18N) => new { Post, PostI18N });

OrderMapper<??> m = OrderMapper.For<??>().Add("title", x => x.Title);

Where x must be of type AnonymousObject in listOfAnonymousObjects. My OrderMapper code is:

public class OrderMapper {
  public static OrderMapper<T> For<T>() {
    return new OrderMapper<T>();
  }
}

public class OrderMapper<T> {

  private readonly Dictionary<String, LambdaExpression> _mappings = new Dictionary<String, LambdaExpression>();

  public OrderMapper<T> Add<K>(String source, Expression<Func<T, K>> target) {

    if (!_mappings.ContainsKey(source))
      _mappings.Add(source, target);
    return this;
  }

  public LambdaExpression this[String source] {
    get {
      LambdaExpression target;
      return _mappings.TryGetValue(source, out target) ? target : null;          
    }
  } // this

}

How to do this?

like image 695
Miguel Moura Avatar asked May 09 '17 11:05

Miguel Moura


1 Answers

You can take advantage of type inference, but that requires you to pass along an instance. This could do:

public static OrderMapper<T> ForFromEnumerable<T>(IEnumerable<T> dummy)
{
    return new OrderMapper<T>();
}

Usage:

var m = OrderMapper.ForFromEnumerable(listOfObjectsOfTypeY).Add("title", x => x.Title);
like image 167
Patrick Hofman Avatar answered Sep 30 '22 22:09

Patrick Hofman