The idea is simple: you should provide one more parameter (method parameter, not generic parameter): the delegate instance converting the element of the type
T1
to the type
T2
. Your type constraints for
T1
and
T2
are absolutely redundant and useless. You can work with elements of any types, not just classes.
Your delegate-type parameter should itself be generic, using the same generic parameters,
T1
and
T2
:
public static class SomeExtensionUtility {
public static List<T2> ConvertList<T1, T2>(
this List<T1> list,
System.Func<T1, T2> convertor) {
return
}
}
The implementation is simple: you convert elements in source collection to
T2
add then to the target collection, one by one, in a loop. I replaced
Collection
with
List
just for example, because
Collection
is probably some your type which I don't have.
By the way, it is not quite clear why did you call your class
CollectionExtension
:-).
It won't work this way, because you operator, as the operator of the static class, won't compile. But my class can be used as the extension class.
[EDIT]
The usage of this extension method won't be different from any other extension method:
using MyExtensionMethods;
using System.Collections.Generic;
List<string> stringList = new List<string>();
List<int> intList = stringList.ConvertList<string, int>(
(stringValue) => { return int.Parse(stringValue); }
);
For some background, please also read:
http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29[
^],
http://msdn.microsoft.com/en-us/library/dd799517%28v=vs.110%29.aspx[
^].
This covariance/contravariance matter is really non-trivial, but the problem and the solution I demonstrated are trivial enough.
—SA