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?
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.
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 + ">"));
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() + ">");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With