Search code examples
c#wpflinqdatatableilist

Compare datatable to IList


I have a DataTable, called dt, that has two columns and is populated by reading data from a CSV file. The 2 columns are Keys and their respective Descriptions approximately 7000 rows.

Now I have IList<string> keys, which is nothing but keys (same keys as in the DataTable).

How do I match the IList<string> keys to the DataTable and retrieve a final output as a new DataTable that has only the rows matching with the IList?


Solution

  • You can use:

    DataTable filtered = dt.AsEnumerable()
                            .Where(r => list.Contains(r.Field<int>("id")))
                            .CopyToDataTable();
    

    You can also create a HashSet<T> and use that in your query.

    List<int> list = new List<int>();
    //.... ids in the list
    
    HashSet<int> hashSet = new HashSet<int>(list);
    DataTable filtered = dt.AsEnumerable()
                            .Where(r => hashSet.Contains(r.Field<int>("id")))
                            .CopyToDataTable();