I have a object of type.
class A
{
public int Id{get;set;}
public decimal? Num {get;set;}
}
Then I have List<A> objList
data populated from db .
I need to make Num as positive number , so
I tried to do the following.
objList = objList.ForEach(x=>x.Num = Math.Abs(x.Num));
Since the Num is nullable decimal , I am not able to use it in Linq. How Can I use it so that I can skip null values and convert -ve values to +ve one using Math.abs?
3
Answers
ForEach
is not LINQ, it’s an instance method onList<T>
which updates the list in place.You could use a ternary expression to only apply
Math.Abs
whenNum
is not null:ForEach
is not part of LINQ but rather a method defined onList<T>
and it returnsvoid
(so you can’t assign it’s result toobjList
i.e.objList = objList.ForEach
).You can use ternary operator with check for
x.Num
having value and use that value forMath.Abs
:I wouldn’t use
List<T>.ForEach()
to mutate the list. Instead, I’d use a simpleforeach
loop like this:Note: If using nullable checking, you must use
!
to suppress a warning initem.Num!.Value
because the compiler isn’t smart enough to figure out that because of theWhere
it can’t be null.Also note that this approach avoids the redundant assignment of
null
to an already-nullNum
which occurs for the other solutions.(See Eric Lippert’s post on foreach vs ForEach for some discussion on why you shouldn’t use
List<T>.ForEach()
to mutate a list.)