1

I'm new to C#. I'm trying to get a List.Select to work with async tasks, and I'm getting an error with the Select call. The error says

The type arguments for method 'IEnumerable System.Linq.Enumerable.Select(this IEnumerable, Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

Here's my code:

var lst = new List<string>();
lst.Add("");
lst.Add("");
var tasks = lst.Select(async x =>
{
    await Task.Delay(1000);
    throw new Exception();
});
await Task.WhenAll(tasks);
ewok
  • 20,148
  • 51
  • 149
  • 254
  • It will work in .NET Core. Which runtime are you using? – Pavel Anikhouski Mar 31 '20 at 19:05
  • I cannot reproduce. What .NET version are you running this on? – Emanuel Vintilă Mar 31 '20 at 19:05
  • I agree about asking the .NET platform/version used. I have deleted my own answer, but I assume the asker compile his code on .NET Framework, because the error usually happens on .NET Framework. – Eriawan Kusumawardhono Mar 31 '20 at 19:11
  • .NET Framework 4.7.1 – ewok Mar 31 '20 at 19:15
  • The simple answer is that your `Select` isn't returning anything, so the compiler can't determine what `T` should be. I'm not sure why you `throw new Exception();` but if you replace that line with `return x;` it should at least build. – rfmodulator Mar 31 '20 at 19:56
  • 1
    I'm throwing the exception because what I'm testing is the exception handling of async methods inside a select. But you're right, I added `return x` and it works. – ewok Mar 31 '20 at 19:57
  • @ewok As long as there is a `return [value];` statement, then it will build, even if it's unreachable (i.e. an exception is thrown). – rfmodulator Mar 31 '20 at 20:01
  • @ewok "testing is the exception handling of async methods inside a select"? Select does not execute anything... (just making sure you know) – Alexei Levenkov Mar 31 '20 at 21:24
  • @AlexeiLevenkov but `Task.WhenAll` does – ewok Mar 31 '20 at 21:31

0 Answers0