linjunshi
linjunshi

Reputation: 87

List.Foreach() complains cannot convert from 'void' to 'object'

When I tried to run the following code, it tells me the 'cannot convert from 'void' to 'object' on the last line, does anyone know what is wrong with the code?

public static void Main(string[] args)
{
    string s = "asfdsanfdjsajfois";
    Dictionary<char, int> dict = new Dictionary<char, int>();
    s.ToCharArray().ToList().ForEach(a => {
        dict[a] = (dict.ContainsKey(a)) ? dict[a]+1 : 1;
    });
    pln(dict.Keys.ToList().ForEach(a => Console.WriteLine(dict[a])));
}

Upvotes: 1

Views: 2011

Answers (2)

Zein Makki
Zein Makki

Reputation: 30022

The problem is clear without providing any more information:

dict.Keys.ToList().ForEach(a => Console.WriteLine(dict[a])) is a statement that doesn't return anything void, and you're passing that to the pln function, that functions accepts and an argument of type object. You need to pass it an object for that type in order to make the compiler happy and for the code to make sense.

Upvotes: 3

sujith karivelil
sujith karivelil

Reputation: 29026

Take a look into this part: .ForEach(a => Console.WriteLine(dict[a]); through this you are iterating through each keys in the Dictionary and print them to the console. Actually the Console.WriteLine() method's return type is void which means it is not returning anything. But you are trying to pass something to a method called pln But it is not specified in the question that how the method is defined or what's the value you are expected in that method.

Actually you need not to iterate through keys and then collect values, you can directly fetch values like this:

dict.Select(x=>x.Value).ToList()

If you need to pass each values to the plan method then you should modify the pln method signature like the following:

 private static void pln(int p)
 {
     Console.WriteLine(p);
    // Do something here
 }

And for this the query will be like dict.ToList().ForEach(x => pln(x.Value));

If you want to pass the values as List then the method signature will be :

private static void pln(List<int> p)
{
  // Do something here
}

And for this the query will be like pln(dict.Select(a => a.Value).ToList());

Upvotes: 0

Related Questions