问题描述:

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.

网友答案:

You could use Math.Max for that:

parameter1inItemsStruct = Math.Max(0, x.intno1),
parameter1inItemsStruct = Math.Max(0, x.intno2)
网友答案:

Use ?: Operator

{
    parameter1inItemsStruct = x.intno1 > 0 ? x.intro1 : 0,
    parameter1inItemsStruct = x.intno2 > 0 ? x.intro2 : 0

}
网友答案:

Try:

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

Data.Items = dataToAdd.maindata
.select(x => new Data.ItemsStruct
{

parameter1inItemsStruct = x.intno1<0?0:x.intno1,
parameter1inItemsStruct = x.intno2<0?0:x.intno2

});

}
网友答案:

Something like this: parameter1inItemsStruct = x.intno1 < 0 ? 0 : x.intno1

相关阅读:
Top