Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot assign void to an implicitly-typed local variable

var query = rep.GetIp()  // in this line i have the error
           .Where(x => x.CITY == CITY)
           .GroupBy(y => o.Fam)
           .Select(z => new IpDTO
                        {
                            IId = z.Key.Id,
                            IP = z.Select(x => x.IP).Distinct()
                        })
           .ToList().ForEach(IpObj => IpObj.IP.ToList().ForEach(ip => PAINTIP(ip)));

When I run this code I have the error:

Cannot assign void to an implicitly-typed local variable

I googled and found that it is a type issue because foreach is not a LINQ function? I cannot understand where the void is!

like image 794
Tania1990 Avatar asked Nov 23 '11 13:11

Tania1990


3 Answers

  • ForEach() has type void.

  • Select() returns IEnumerable<T>, ToList() returns List<T>, etc.

so:

List<X> x = ...Select(x => x).ToList(); // List<T>

or

x.ForEach(x => x); // void

because you can't assign void to List<T>.


var query = rep.GetIp()  // in this line i have the error
           .Where(x => x.CITY == CITY)
           .GroupBy(y => o.Fam)
           .Select(z => new IpDTO
                        {
                            IId = z.Key.Id,
                            IP = z.Select(x => x.IP).Distinct()
                        });

foreach (var dto in query)
{
    foreach (var ip in dto.IP)
    {
        PAINTIP(ip);
    }
}

or

var query = ....
           .SelectMany(z => z.Select(x => x.IP).Distinct());

foreach (var ip in query)
{
    PAINTIP(ip);
}
like image 64
abatishchev Avatar answered Oct 30 '22 17:10

abatishchev


ForEach() does not return anything. Its type is void.

Try replacing your ForEach() calls with Select().

like image 7
jrummell Avatar answered Oct 30 '22 18:10

jrummell


I saw your other questions, wherein you have asked similar question for the same query. The code partially looks like this :

var Q = rep.GetIp()
        .Where(x => x.CITY == CITY)
        .GroupBy(y => o.Fam)
        .Select(z => new IpDTO
        {
          IId = z.Key.Id,
          IP = z.Select(x => x.IP).Distinct()
       });

Looks like you have used the answer as such and you are trying to assign the returned value from the query to the variable "Q". Check out your previous post : syntax in LINQ IEnumerable<string>

As others have said, ForEach return type is "void". You should call "ForEach", once the variable "Q" is initialized with the collection.

like image 1
Pawan Mishra Avatar answered Oct 30 '22 18:10

Pawan Mishra