Linq query for datatable

Hi,
I have an excel file which I read to a datatable say dt_original. Now based on value in column A I want to segregate it into two datatables. If the cell of column A contains the keyword lets say “abc” then the whole row goes to datatable1 else datatable2. Now column A can have blank cells as well.
Can we write this logic using linq query?

Hi @SunnyJha

Filter the DataTable based on the values in column A containing the keyword “abc”

 dt1 = dt_original.AsEnumerable().
    Where(Function(row) Not row.IsNull("Column A") AndAlso row.Field(Of String)("Column A").Contains("abc")).
    CopyToDataTable()

Filter the DataTable based on the values in column A not containing the keyword “abc”

dt2 = dt_original.AsEnumerable().
    Where(Function(row) Not row.IsNull("Column A") AndAlso Not row.Field(Of String)("Column A").Contains("abc")).
    CopyToDataTable()

Regards,

1 Like

Hi @SunnyJha

You can use the LinQ Expression,

-> Datatable1 = dt_Original.AsEnumerable().where(Function(X) (Not String.IsNullOrEmpty(X("ColumnA").ToString)) AndAlso X("ColumnA").toString.Equals("Keyword")).Copytodatatable()

-> Datatatble2 = dt_Original.AsEnumerable().Where(Function(x) (Not String.IsNullOrEmpty(x("ColumnA").ToString)) AndAlso (Not x("ColumnA").ToString().Equals("Keyword"))).CopyToDataTable()

→ Datatable1 contains the matched rows with the keyword in ColumnA.
→ Datatable2 contains the unmatched rows with the keyword in ColumnA.
→ Change the Column name and Keyword in the LinQ Expression based on your condition.

Hope it helps!!

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