Filter the Datatable using Linq

How to filter data in datatable1 based on the condition of datatable2 using LINQ?
get the solution for this problem.

@SRILAHARI_8

can you provide what was your input and expected output

Hi @SRILAHARI_8 ,

Please test the below linq query

var dt_result = dt1.AsEnumerable()
.Where(r => dt2.AsEnumerable()
.Any(r2 => r.Field(“Column1”) == r2.Field(“Column1”)))
.CopyToDataTable();

Here’s a breakdown of what the code does:

  1. dt1.AsEnumerable(): This converts the rows of DataTable dt1 into an enumerable collection of DataRow objects. This is necessary because LINQ queries operate on enumerable collections.
  2. dt2.AsEnumerable(): Similarly, this converts the rows of DataTable dt2 into an enumerable collection of DataRow objects.
  3. .Where(r => dt2.AsEnumerable().Any(r2 => r.Field<string>("Column1") == r2.Field<string>("Column1"))): This is the core of the LINQ query. It filters the rows of dt1 based on a condition. The condition is specified by a lambda function r => dt2.AsEnumerable().Any(r2 => r.Field<string>("Column1") == r2.Field<string>("Column1")), which returns true for rows of dt1 where the value in the “Column1” field is equal to the value in the “Column1” field of any row in dt2.
  4. .CopyToDataTable(): This converts the filtered enumerable collection of DataRow objects back into a DataTable

Regards
Happy Automation

@SRILAHARI_8

you can refer this

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