Compare DataRow collection to List<T>

Jon picture Jon · Jan 5, 2010 · Viewed 13.7k times · Source

I have a List<string> and I have a DataTable.

One of the columns in a DataRow is ID. The List holds instances of this ID.

The DataTable gets populated on a Timer.

I want to return items from the List that are not in the DataTable into another list.

Answer

bdowden picture bdowden · Jan 5, 2010

You will want to do something like this

var tableIds = table.Rows.Cast<DataRow>().Select(row => row["ID"].ToString());

var listIds = new List<string> {"1", "2", "3"};

return listIds.Except(tableIds).ToList();

You can cast the rows in the data table to be an IEnumerable collection and then select the "ID" column value from each of them. You can then use the Enumerable.Except extension method to get all of the values from the List that are not in the collection you just made.

If you need to get the values that are in the table but not the list, just reverse listIds and tableIds.