I have a list and I'm trying to set one boolean
field status to true
if the name field is not haha. Below is what I thought it suppose to work but apparently it's not:
ObjectList.ForEach(x => !x.name.Equals("haha")).status = true;
I'm getting the following error:
Only assignment, call, increment, decrement, await...can be used as a statement
May I know which part is wrong in my expression?
That certainly wouldn't do what you wanted it to. ForEach
doesn't return anything. It executes the delegate you provide against each item in the list, and that's all.
Personally I'd just use Where
with a foreach
loop:
foreach (var item in ObjectList.Where(x => x.name != "haha"))
{
item.status = true;
}
The exact error itself is because of the !
part of your expression. The action you execute in ForEach
is of type Action<T>
. So you've effectively got:
Action<Foo> action = x => !x.name.Equals("haha");
That's invalid in the same way that this statement would be invalid:
!x.name.Equals("haha"); // Invalid
A unary !
expression isn't a statement expression - you can't use it as a statement on its own. If you just had:
x.name.Equals("haha");
then it would be valid as a method invocation statement - but still useless.
See more on this question at Stackoverflow