I'm trying to convert the following method to an extension method on IEnumerable:
private static IEnumerable<TTarget> MapList<TSource, TTarget>(IEnumerable<TSource> source)
{
return source.Select(
element =>
_mapper.Map<TSource, TTarget>(element)
).ToList();
}
Right now it's called like this:
var sourceList = new List<SourceType>();
return MapList<SourceType, TargetType>(sourceList);
But I want to call it like this:
var sourceList = new List<SourceType>();
return sourceList.MapTo<TargetType>();
I have tried doing this:
public static IEnumerable<TTarget> MapTo<TTarget>(this IEnumerable<TSource> source)
{
return source.Select(
element =>
Mapper.Map<TSource, TTarget>(element)
).ToList();
}
But I get type or namespace TSource
not found since it's not included in the method's type parameter list. I can make it work like this:
public static IEnumerable<TTarget> MapTo<TSource, TTarget>(this IEnumerable<TSource> source)
{
return source.Select(
element =>
Mapper.Map<TSource, TTarget>(element)
).ToList();
}
But this I have to call it like this:
var sourceList = new List<SourceType>();
sourceList.MapTo<SourceType, TargetType>();
Which I feel is not as clear as sourceList.MapTo<TargetType>()
.
Is there any way to do what I want?