Reputation: 11393
I have two DataTable
s. I want to get what exists in the first one but does not exist in the second one. I would like the results in another DataTable
. I would like to use LINQ.
DataTable dt1 = cc1roleDAL.GetAll(x, 0);
DataTable dt2 = cc1roleDAL.GetSpecific(x);
Note: the column names I return from the the two datatables:
crs_name
name
Upvotes: 2
Views: 12241
Reputation: 21654
This will do the trick for you:
var rowsOnlyInDt1 = dt1.AsEnumerable().Where(r => !dt2.AsEnumerable()
//make sure there aren't any matching names in dt2
.Any(r2 => r["crs_name"].Trim().ToLower() == r2["crs_name"].Trim().ToLower() && r["name"].Trim().ToLower() == r2["name"].Trim().ToLower()));
or if you prefer query syntax:
var rowsOnlyInDt1 = from r in dt1.AsEnumerable()
//make sure there aren't any matching names in dt2
where !dt2.AsEnumerable().Any(r2 => r["crs_name"].Trim().ToLower() == r2["crs_name"].Trim().ToLower() && r["name"].Trim().ToLower() == r2["name"].Trim().ToLower())
select r;
You can then put the results into a DataTable by using the CopyToDataTable function:
DataTable result = rowsOnlyInDt1.CopyToDataTable();
Upvotes: 5
Reputation: 752
HI there hope this code does help you and if i have misunderstood then can ask me to edit this post
DataContext db = new DataContext();
var result = from a in db.dt1
from b in db.dt2
where a.crs_name != b.name
select a.crs_names;
foreach(var names in result)
{
dt2Entity obj = new dt2Entity();
obj.name = names.name;
db.InsertOnSubmit(obj);
db.SubmitChanges();
}
Upvotes: 0
Reputation: 35696
You want to use the Except
extension.
Here is the link to the linq on MSDN.
From what I get from the question somthing like.
var theNonIntersect =
dt1.AsEnumerable().select(r => r.Field<string>("crs_name"), r.Field<string>("name"))
.Except(dt2.AsEnumerable().select(r => r.Field<string>("crs_name"), r.Field<string>("name")));
Upvotes: 2