Dan Hall Dan Hall - 1 month ago 5
C# Question

Linq - Set int to 0 if it is a minus number

I'm initialising a class object using Linq, what I need to do is set a value of 0 if I find the value from another class object is a minus number, here's the existing code:

public void fillObject(FillData dataToAdd)
{
Data data = new Data();

Data.Items = dataToAdd.maindata
.select(
x => new Data.ItemsStruct
{
parameter1inItemsStruct = x.intno1,
parameter1inItemsStruct = x.intno2
});
}


intno1
or
intno2
can be any value but if the value is a negative number I want to set it to 0.

Does anyone have any idea how this can be acheived in
LINQ
? What I don't want to do is directly reference each parameter in the object and check/alter its value, I just want to check/change the value 'inline' with
Linq
.

Answer

You could use Math.Max for that:

parameter1inItemsStruct = Math.Max(0, x.intno1),
parameter1inItemsStruct = Math.Max(0, x.intno2)
Comments