if i have two datatables :
DT1 & DT2
How to check if the first one contains the second one , i mean that the same rows of DT2
is in the DT1
.
if i have two datatables :
DT1 & DT2
How to check if the first one contains the second one , i mean that the same rows of DT2
is in the DT1
.
loop through the tables and comapare fields (hopefully just the IDs). there are a number of ways to do this depending on how your datatables are structured.
My question: "Must all row's fields match with the same row's fields of the other DataTable?"
Your answer: "no just the id"
You can first check if both DataTables
are null or both have the same row-count. Then you can use LINQ to determine if both have the same IDs using Enumerable.Except
:
var dt1IDs = DT1.AsEnumerable().Select(r => r.Field<int>("id"));
var dt2IDs = DT2.AsEnumerable().Select(r => r.Field<int>("id"));
var diff = dt1IDs.Except(dt2IDs);
var equal = DT1.Rows.Count == DT2.Rows.Count && !diff.Any();
Explanation: diff.Any()
returns true when there's at least one id in DT1 that is not in DT2.
Edit: If the ID is not unique and might repeat you need to check whether all ID's in DT1 are also in DT2 and all IDs of DT2 are in DT1:
var DT1InDT2 = dt1IDs.Except(dt2IDs);
var DT2InDT1 = dt2IDs.Except(dt1IDs);
var equal = DT1.Rows.Count == DT2.Rows.Count && !DT1InDT2.Any() && !DT2InDT1.Any();
This query is efficient anyway.
Edit2: I've just seen that i've misunderstood your requiremnet a little bit. You only want to know if the first table contains the second, not vice-versa.
var DT2IdNotInDT1 = dt2IDs.Except(dt1IDs);
var equal = !DT2IdNotInDT1.Any();
you can use Intersect operator
var intersect = DT2.AsEnumerable().Intersect(DT1.AsEnumerable(), DataRowComparer.Default);