Unable to cast from type 'System.double' to 'System.String.'

Firstly, Apologies for the duplicate topic but I tried all the solutions mentioned.

So, I have got 2 datatables using which I am performing operation like finding matched & Unmatched records using LINQ, I have always used the same LINQ and worked fine until now.

To get matched
dt1.AsEnumerable().Where(function(row) dt2.AsEnumerable().Select(function(r) r.Field(Of String)(“Contract no.”.ToString.Trim)).Any(function(x) x = row.Field(Of String)(“Contract no.”.ToString.Trim))).CopyToDataTable

To get unmatched
dt1.AsEnumerable().Where(function(row) NOT dt2.AsEnumerable().Select(function(r) r.Field(Of String)(“Contract no.”.ToString.Trim)).Any(function(x) x = row.Field(Of String)(“Contract no.”.ToString.Trim))).CopyToDataTable

Sample data attached.

When I got the error I changed .to string to .To double(Not recommended though) still I got error saying cast is not valid.

if I remove the field of part, it works for matched but unmatched does not work.

Any suggestion will be very helpful.Test.xlsx (10.5 KB)

@Faraz_Subhani
please do a check what it is doing once yo have removed the row with the empty value

Let us know the result

Thanks for the reply, actually I already did that, actual data doesn’t have any blank rows, in attached sheet I deleted the data by mistake.

currently we do not know the exact error. In general we would do / adopt the code

  • defensive handling of unneeded spaces with trim
  • defensive handling of nulls

Please can you suggest any edits to my above code or please if you got time can you try from your end, I have attached the test data.

@Palaniyappan please any suggestion on this?

@Faraz_Subhani

row.Field(Of String)(“Contract no.” ) .ToString.Trim)

check your syntax on this part.
Have a look here on shortening the statement with the help of query syntax:
grafik

1 Like

Thank you very much for this optimized LINQ, it worked, thanks for your help, keep up the good work,

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.