Search code examples
c#linqdatatablerowfilter

Filtering data table for multiple values


I have 2 datatables objdatatable1 and objdatatable2 .

I need to filter the data in objdatatable2 such that market_id in objdatatable2 should not be in objdatatable1.

I am even to open to linq which will filter the contacts on not in clause


Solution

  • This copies to DataTable dt all rows from objectdatatable2 which have values in the 'market_id' field which do not appear in a field of the same name in objectdatatable1. In this edit the 'market_id' field is of type string in objectdatatable2 and of type int in objectdatatable1.

    // This creates an empty DataTable with the same structure as objdatatable2.
    DataTable dt = objdatatable2.Clone();
    
    var results = objdatatable2.AsEnumerable().Where(r2 => !objdatatable1.AsEnumerable().Any(r1 => (r2.Field<string>("market_id") == r1.Field<int>("market_id").ToString())));
    // Copy results to the DataTable only if there are results.
    if (results.Count() > 0) {
        dt = results.CopyToDataTable();
    }