Home > Net >  Using Math.Abs on nullable decimal property
Using Math.Abs on nullable decimal property

Time:12-15

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?

CodePudding user response:

ForEach is not part of LINQ but rather a method defined on List<T> and it returns void (so you can't assign it's result to objList i.e. objList = objList.ForEach ).

You can use ternary operator with check for x.Num having value and use that value for Math.Abs:

objList.ForEach(x => x.Num = x.Num.HasValue ? Math.Abs(x.Num.Value) : null);

CodePudding user response:

ForEach is not LINQ, it's an instance method on List<T> which updates the list in place.

You could use a ternary expression to only apply Math.Abs when Num is not null:

objList.ForEach(x => x.Num = x.Num is decimal d ? Math.Abs(d) : null);

CodePudding user response:

I wouldn't use List<T>.ForEach() to mutate the list. Instead, I'd use a simple foreach loop like this:

foreach (var item in objList.Where(item => item.Num != null))
{
    item.Num = Math.Abs(item.Num!.Value);
}

Note: If using nullable checking, you must use ! to suppress a warning in item.Num!.Value because the compiler isn't smart enough to figure out that because of the Where it can't be null.

Also note that this approach avoids the redundant assignment of null to an already-null Num 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.)

  • Related