Linq query to update data table if the column value is negative

I am looking for the linq query to update data table if the column value is negative without the invoke code

Hi @ankitdwivedi02

Your query is quite confusing, could you bre more specifc.

If possible better to provide the Input data and excepted output for our understanding.

@ankitdwivedi02

Please share the input and output Sheet for reference

@rlgandu - I have a datatable in which if one of the column contains negative value for any row, I need to replate it with 0 and for this, I want to use linq query rather than the for loop

@ankitdwivedi02,

Use this LINQ

(From row In dt.AsEnumerable()
 Select
     row.ItemArray = 
     row.ItemArray.Select(Function(value, index) 
         If(index = dt.Columns("Amount").Ordinal AndAlso Convert.ToDouble(value) < 0, 
            0, 
            value
         )
     ).ToArray()
).CopyToDataTable()

Thanks,
Ashok :slight_smile:

Okay @ankitdwivedi02

Yes, it’s possible to do it in LINQ Expressions, But it’s better to share the Input data and Expected output, But try the below LINQ Expression.

Check the below LINQ Expression,

- Assign -> dt_Output = (From row In Input_dt.AsEnumerable 
                         Let ValuetoUpdate = If(CDbl(row("Column name").ToString())<0, "0", row("Column name").toString)
                         Let newRow = Input_dt.Clone().Rows.Add(row.ItemArray.Select(Function(column) If(column.Equals(row("Column name")), ValuetoUpdate, column)).ToArray()) 
                         Select newRow).CopyToDataTable()

Change the Column name in the Expression with your column name where I have mentioned column name.

Hope you understand!!

we recommend to check more for the options available for updating a column value and then deciding which approach is fitting to your scenario

@ankitdwivedi02

(From row In DT.AsEnumerable()
                   Let newValue = If(CDec(row("ColumnName").ToString()) < 0, "0", row("ColumnName").ToString())
                   Select DT.Clone().Rows.Add(row.ItemArray.Select(Function(column) If(column.Equals(row("ColumnName")), newValue, column)).ToArray())).CopyToDataTable()

image

@mkankatala - Thanks this works for me

1 Like

It’s my pleasure… @ankitdwivedi02

Make my post Mark as solution to close the loop. Then it will be helpful for who are searching for the same solution.

Happy Automation!!