1

This must be simple but I failed to understand why this is not allowed:

var testList = new List<int> { 2, 3, 400, 304, 50, 41 };
testList.Select(x => Console.WriteLine(x));

But this is fine:

testList.Select(x => x * 2);

Where do I misunderstand LINQ to cause this confusion?

rageit
  • 3,513
  • 1
  • 26
  • 38
dragonfly02
  • 3,403
  • 32
  • 55
  • A select statement manipulates the list and returns a new one. You should use ForEach on a List type – Measurity Aug 21 '14 at 21:12
  • Related: [LINQ equivalent of foreach for IEnumerable](http://stackoverflow.com/questions/200574/linq-equivalent-of-foreach-for-ienumerablet) – Kirk Woll Aug 21 '14 at 21:14
  • You might want to use `testList.ForEach(i => Console.WriteLine(i))` – Tim Schmelter Aug 21 '14 at 21:15
  • 2
    LINQ is a language for *asking questions*, not for *causing side effects*. Do not use LINQ expressions as control flow that produces side effects; there is a perfectly good `foreach` loop that already means "cause a side effect for each member of this collection". – Eric Lippert Aug 21 '14 at 21:43

2 Answers2

9

The problem is that the function you pass to Select() must return a value, because the purpose of Select() is to project the elements of a sequence into some other value. But Console.WriteLine(x) returns void (no value).

cdhowie
  • 158,093
  • 24
  • 286
  • 300
8

.Select takes a Func<TSource, TResult> (a lambda that takes a TSource and returns TResult).

Since Console.WriteLine is void, your lambda does not return anything and therefore doesn't meet the requirements.

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
  • 2
    (Nitpick: The lambda has no particular type, because the compiler cannot infer the delegate type. It could be implicitly converted to an `Action` but it could just as easily implicitly converted to some other delegate type that accepts a single parameter of *any* type and returns `void`.) – cdhowie Aug 21 '14 at 21:15
  • @cdhoie: like your comment here because the error from compiler is actually the parameter type can't not be inferred, try explicit type parameter. The error message can be slightly confusing but guess this is not a common error... thanks! – dragonfly02 Aug 21 '14 at 22:11