public static IEnumerable<TV> To<TU, TV>(this IEnumerable<TU> source) where TV : new(TU)
{
return source.Select(x => new TV(TU));
}
The problem is that I can't give the new(TU) constraints.
I've got two approaches for you:
Firstly using Activator.CreateInstance
public static IEnumerable<TV> To<TU, TV>(this IEnumerable<TU> source)
{
return source.Select(m => (TV) Activator.CreateInstance(typeof(TV), m));
}
Secondly, you could use interfaces to define properties rather than use parameterized constructors:
public interface IRequiredMember
{}
public interface IHasNeccesaryMember
{
IRequiredMember Member
{
get;
set;
}
}
public static IEnumerable<TV> To<TU, TV>(this IEnumerable<TU> source)
where TV : IHasNeccesaryMember, new()
where TU : IRequiredMember
{
return source.Select(m => new TV{ Member = m });
}
The first method works but feels dirty and there is the risk of getting the constructor call wrong, particularly as the method is not constrained.
Therefore, I think the second method is a better solution.
Maybe pass in a Func which can create a TV from a TU:
public static IEnumerable<TV> To<TU, TV>(
this IEnumerable<TU> source,
Func<TU, TV> builder)
where TV : class
{
return source.Select(x => builder(x));
}
and call with
tus.To(x => new TV(x));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With