Home > Enterprise >  Is there a method to convert each element of source array from one type to another type?
Is there a method to convert each element of source array from one type to another type?

Time:05-23

This Transfrom function transforms each element of source array from one type to another type by some rule. It has 2 parameters, one of them is an Interface

public static TResult[] Transform<TSource, TResult>(this TSource[] source, ITransformer<TSource, TResult> transformer)
        {
            if (source == null || transformer == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (source.Length == 0)
            {
                throw new ArgumentException("Array is empty");
            }

            var res = Array.ConvertAll(source, transformer.Transform(source));

            return res;
        }

There is an error because parameter of transformer.Transform(source) cannot convert from TSource[] to TSource

Here is the interface ITransformer

public interface ITransformer<in TSource, out TResult>
    {
        TResult Transform(TSource obj);
    }

CodePudding user response:

The ConvertAll docs shows that the method has the following signature:

public static TOutput[] ConvertAll<TInput,TOutput> (TInput[] array, Converter<TInput,TOutput> converter);

As you can see, it takes a Converter<TInput, TOutput>. If we look at the docs for that, we can see that it's a delegate with the following signature:

public delegate TOutput Converter<in TInput,out TOutput>(TInput input);

So you should be able to rewrite your convert line like this:

var res = Array.ConvertAll(source, new Converter<TSource, TResult>(transformer.Transform));

Try it online

  • Related