-1

Writing this function:

static TResult reduce<TSource, TResult>(ParallelQuery<TSource> source,
                                        Func<TResult> seedFactory,
                                        Func<TResult, TSource, TResult> aggregator) {
    return source.Aggregate(seedFactory, aggregator, aggregator, x => x);
}                

but I get a compilation error:

Error 1 The type arguments for method 'System.Linq.ParallelEnumerable.Aggregate(System.Linq.ParallelQuery<TSource>, TAccumulate, System.Func<TAccumulate,TSource,TAccumulate>, System.Func<TAccumulate,TAccumulate,TAccumulate>, System.Func<TAccumulate,TResult>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

The overload I want to use is this one while the compiler seems to think it can be this one too.

How can I help it?

leppie
  • 115,091
  • 17
  • 196
  • 297
mookid
  • 1,132
  • 11
  • 19
  • 3
    I believe that you've put less than nothing effort to solve the issue yourself. Read again what error says and I believe it should be enough....... – Matías Fidemraizer Apr 24 '15 at 13:16
  • @MatíasFidemraizer It seems that I was looking at the wrong place when I tried to solve this issue. I also asked one coworker, who did not find the problem either; I do not have the habit to copy paste every problem I get in here. – mookid Apr 24 '15 at 13:33
  • I don't doubt that, but think compiler errors are there to solve your issues. When I've checked your error message and I've seend "cannot be inferred from the usage" I instantly knew what was going on. At the end of the day, if you read C# compiler errors carefully you'll save a lot of time! :) – Matías Fidemraizer Apr 24 '15 at 15:30

1 Answers1

5

The problem is your third argument - the fourth parameter for in the method declaration. That's declared as:

// Note: type parameter names as per Aggregate declaration
Func<TAccumulate, TAccumulate, TAccumulate> combineAccumulatorsFunc

But you're trying to pass in a

// Note: type parameter names as per reduce declaration
Func<TResult, TSource, TResult> aggregator

That's not valid unless the compiler knows that TResult is convertible to TSource.

Basically, your method only takes a single aggregation function - how to combine the accumulator so far with another source value to create another accumulator. The method you want to call needs another function which combines two accumulators together to create another accumulator. I think you're going to have to take another parameter in your method for this to work.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks. I did not realize that there was this kind of type constrain. In my case, taking only one type parameter instead of two gives me the functionality I want. – mookid Apr 24 '15 at 13:25