Miroslav Zadravec
Miroslav Zadravec

Reputation: 3730

Problems with c# lambda inference

I wrote code like this:

System.IO.File.ReadAllLines("c://test.txt")
   .Select(val => Console.WriteLine(val)
);

And I'm getting a compiler error:

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

WriteLine can accept string and object as the parameter, that's probably a source of the error but how do I rewrite it?

Upvotes: 2

Views: 249

Answers (4)

Miroslav Zadravec
Miroslav Zadravec

Reputation: 3730

This answer includes summary of other answers.

There isn't any problem with parameter type, problem is that Select method must return a value and it shouldn't be used in this case. ForEach would be the correct method, but only List has it, not every IEnumerable. So:

System.IO.File.ReadAllLines("c://test.txt")
.ToList()
.ForEach(val => Console.WriteLine(val));

will do the trick (while incurring some overhead by converting to a list).

There is one more way: static Array.ForEach method. So my code will look like this:

Array.ForEach(
System.IO.File.ReadAllLines("c://test.txt"), val => Console.WriteLine(val)
);

Upvotes: 0

abrkn
abrkn

Reputation: 2061

File.ReadAllLines(@"c://test.txt").ToList().ForEach(Console.WriteLine);

Upvotes: 3

EgorBo
EgorBo

Reputation: 6142

You can fix it by this code:

System.IO.File.ReadAllLines("c://test.txt")
   .Select(val => {Console.WriteLine(val); return val;})

or

System.IO.File.ReadAllLines("c://test.txt")
   .ToList().ForEach(val => Console.WriteLine(val));

Upvotes: 3

Thomas Levesque
Thomas Levesque

Reputation: 292555

The Select method takes a Func<TSource, TResult>, but the return type of Console.WriteLine is void, i.e. no value at all. So in that case TResult would be void, and obviously, the return type of Select can't be IEnumerable<void> (i.e. "a sequence of nothing"...)

The lambda expression passed to Select has to return a value. If you just want to print the result of File.ReadAllLines, use a for or foreach loop.

Upvotes: 7

Related Questions