C# Question

What is best way to create converter from function?

I want to apply func object as converter like this:

Func<int, double> f = x => x / 2.5;
Converter<int, double> convert = f;
List<double> applied_list = new List<int>(){1, 2, 3}.ConvertAll(convert);


Compiler gives me such message:


Error CS0029 Cannot implicitly convert type 'System.Func' to 'System.Converter'


What is best way to use function as converter?

Answer Source

There are three options here. In my preferred order, they are:

  • Start using LINQ instead of ConvertAll:

    List<double> appliedList = new List { 1, 2, 3 }.Select(f).ToList();
    
  • Create a converter to start with:

    Converter<int, double> converter = x => x / 2.5;
    List<double> appliedList = new List { 1, 2, 3 }.ConvertAll(converter);
    
  • If you really, really must, create a converter from the function using a delegate creation expression:

    Func<int, double> f = x => x / 2.5;
    Converter<int, double> converter = new Converter<int, double>(f);
    List<double> appliedList = new List { 1, 2, 3 }.ConvertAll(converter);
    

The last option creates a delegate that just wraps the original one.