Change value in DataTable using LINQ or Lambda in c# with conditions

Hello Everyone !

I have some questions for you, first i’m using UiPath in C#, and i want to do multiple things using LINQ or Lambda expression, i would like to have both solution for me to understand what i’m doing wrong.

First i want to apply a function and a if condition with a cast on rows of this DT

Type Number Letter
XA 999 J
XB 200 J
XC 60 J
XD 3 M

All columns are String, If [Letter] = “m” i Want [Number] = [Number]*30.5

Res :

Type Number Letter
XA 999 J
XB 200 J
XC 60 J
XD 91,5 M

Second part is to keep all the rows from a second DT :

ID Type Number
1 XA 400
2 XC 70
3 XD 46

that are > to 50% of the [Number] corresponding with [Type]

Res :

ID Type Number
2 XC 70
3 XD 46

Doing it with a for each etc is fine but i would like to have in C#, a LINQ query, and a Lambda expression for both operation please :slight_smile:

For an introduction into LINQ have a look here:
[HowTo] LINQ (VB.Net) Learning Catalogue - Help / Something Else - UiPath Community Forum

An overview of the different option to update a datacolumn value find here:
[HowTo] Overview on different options for grouping data and processing the groups - News / Tutorials - UiPath Community Forum

When both cases are to do with LINQ (e.g. for learning purpose)

Case 1:

  • DataTable Reconstruction approach
  • parsing number to Double
  • multiply
  • recreate the itemArray
  • add row to the cloned Datatable

Case 2:

  • Where Operator along with number parsing

Let us know if further assistance is needed

give a try at
dtResult = dtData.Clone();

dtResult =

(from d in dtData.AsEnumerable()
let np = Convert.ToDouble(d["Number"].ToString().Trim())
let chk = d["Letter"].ToString().Trim().Equals("M")
let nm = chk ? (np*30.5).ToString() : np.ToString()
let ra = new object[] {d[0], nm, d[2]}
select dtResult.Rows.Add(ra)).CopyToDataTable();

Thanks for your help !

I tried this and have an error :

image

image

And there is no way to directly modify the row without doing a copy ?

as discussed within the Blog

  • less LINQ more C#/.Net Code → Invoke Code

recommended

  • Avoiding / minimizing Black Box Code
  • Filter to the subset of relevant rows is highly recommended
1 Like