Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq ForEach - Returning cannot assign 'void' to an implicitly-typed local variable

Tags:

c#

linq

I'm trying to use a linq query to save myself a few lines of code. I'm getting a compile error where I'm told:

Returning cannot assign 'void' to an implicitly-typed local variable.

var GIANTLIST = new List<string>();

var taskIds = Complaint.Tasks.Select(s => s.Task_ID).ToList().ForEach( s =>
{
    GIANTLIST.Add("<Task_ID=" + s.ToString() + ">");
});

I'm trying to understand the linq query better. I understand that it's got a "void" return type? If this is the case how am I able to then add to the list?

like image 523
this note Avatar asked Jun 05 '15 17:06

this note


3 Answers

Foreach it doesn't return any result; you can't assign it to a variable. Remove var taskIds:

var GIANTLIST = new List<string>();

Complaint.Tasks.Select(s => s.Task_ID).ToList().ForEach( s =>
{
    GIANTLIST.Add("<Task_ID=" + s.ToString() + ">");
});

Here you have microsoft documentation about it https://msdn.microsoft.com/en-us/library/bwabdf9z%28v=vs.110%29.aspx

I'm trying to understand the linq query better. I understand that it's got a "void" return type? If this is the case how am I able to then add to the list?

Think this ForEach as the usual functional ForEach ForEach(var a in MyList) which it doesn't return nothing is a void too. Inside ForEach you can modify directly the variables of your classes.

like image 53
Marc Cals Avatar answered Sep 23 '22 23:09

Marc Cals


that ForEach is not a part of Linq, it is a method of List class

keep it simple

var GIANTLIST = Complaint.Tasks.Select(s => "<Task_ID=" + s.Task_ID + ">").ToList();

if you need to add items to existing list, use AddRange instead of ForEach

GIANTLIST.AddRange(Complaint.Tasks.Select(s => "<Task_ID=" + s.Task_ID + ">"));
like image 29
ASh Avatar answered Sep 24 '22 23:09

ASh


The ForEach method returns void. You are assigning void to the taskIds. If you want to populate taskIds, do this:

            var GIANTLIST = new List<string>();
            var taskIds = new List<int>();
            Complaint.Tasks.Select(s => s.Task_ID).ToList().ForEach( s =>
            {
                taskIds.Add(s.TASK_ID);
                GIANTLIST.Add("<Task_ID=" + s.ToString() + ">");
            });
like image 34
Noel Avatar answered Sep 22 '22 23:09

Noel