Question

Why this code doesn't work?

public static IList<float> CreateModifiedList(IList<float> list)
{
    IList<float> modifiedList= list.Aggregate(new List<float> (), (l, item) =>l.Add(++item));

    return modifiedList;
}

When I try to compile it using Mono I get the following error:

error CS0029: Cannot implicitly convert type void' to System.Collections.Generic.List'

Was it helpful?

Solution

It does not work, because l.Add(++item) is not returning your aggregate (list of float) - it returns void. Second argument should be of type Func<List<float>, float, List<float>>. Change your code to return aggregation variable:

(l, item) => { l.Add(++item); return l; }

BTW What you are doing could be achieved this way:

IList<float> modifiedList = list.Select(item => ++item).ToList();

OTHER TIPS

Change

l.Add(++item)

to

{ l.Add(++item); return l; }

As you need to return a list out the back of the aggregation.

Per the signature of IEnumerable.Aggregate, the second parameter should be a Func<TSource, TSource, TSource> - in your case, (float, float) => float. But List.Add is a void function, and does not return a float. Hence the compilation error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top