Compare the DataRow collection with List <T>
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
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
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