Compare the DataRow collection with List <T>

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

One of the columns in the DataRow is an identifier. The list contains instances of this identifier.

The DataTable is populated with a timer.

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

+4
source share
3 answers

You need 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 distinguish rows in the data table as IEnumerable collections, and then select the value of the "ID" column from each of them. Then you can use the Enumerable.Except extension method to get all the values ​​from the list that are not in the collection that you just made.

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

+12
source

If your table was something like this:

 DataTable dt = new DataTable(); dt.Columns.Add("ID"); DataRow dr = dt.NewRow(); dt.PrimaryKey = new DataColumn[] {dt.Columns[0]}; dr["ID"] = "1"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["ID"] = "2"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["ID"] = "3"; dt.Rows.Add(dr); 

and the list was something like this:

 List<string> ls = new List<string>{"1","2","4"}; 

we could get the elements found in the list and not in the datatable in this way:

 var v = from r in ls where !dt.Rows.Contains(r) select r; v.ToList(); 
+1
source

With reasonable efficiency through a HashSet<T> (and noting that the fastest way to get data from a DataRow through a DataColumn index):

  HashSet<int> ids = new HashSet<int>(); DataColumn col = table.Columns["ID"]; foreach (DataRow row in table.Rows) { ids.Add((int)row[col]); } var missing = list.Where(item => !ids.Contains(item.ID)).ToList(); 
+1
source

All Articles