Reputation: 493
I have below code, that has a datatable dt
. And I have one more datatable named dt1
. I want to check dt
has dt1
data before merge both table. If dt
already has dt1
data I don't want to merge both datatable.
Ideally looking for a dt.Exists(dt1)
like code.
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[6] { new DataColumn("ID", typeof(int)),
new DataColumn("Acount", typeof(string)),
new DataColumn("Name", typeof(string)),
new DataColumn("Quarter", typeof(string)),
new DataColumn("FY", typeof(int)),
new DataColumn("Income_percent", typeof(int))});
dt.Rows.Add(1, "ABC", "Ram", "Q1", 2011, 50);
dt.Rows.Add(2, "XYZ", "Hari", "Q4", 2011, 35);
dt.Rows.Add(3, "ABC", "Rohit", "Q3", 2011, 40);
dt.Rows.Add(4, "ABC", "Ram", "Q2", 2011, 25);
dt.Rows.Add(5, "XYZ", "Hari", "Q3", 2011, 60);
DataTable dt1 = new DataTable();
dt1.Rows.Add(3, "ABC", "Rohit", "Q3", 2011, 40);
dt1.Rows.Add(4, "ABC", "Ram", "Q2", 2011, 25);
dt1.Rows.Add(5, "XYZ", "Hari", "Q3", 2011, 60);
}
}
Upvotes: 0
Views: 1861
Reputation: 7005
It looks like your data is based on the ID column. In such case you can use Linq to compare both data tables:
IEnumerable<int> idsInDt = dt.AsEnumerable().Select(row => (string)row["ID"]);
IEnumerable<int> idsInDt1 = dt1.AsEnumerable().Select(row => (string)row["ID"]);
IEnumerable<int> newRows = idsInDt1.Except(idsInDt);
Then you simply need to verify the count and merge new lines based on ID
if(newRows.Count > 0)
// Copy new lines
Upvotes: 1
Reputation: 7591
you can use below menioned code
var diff = dt.AsEnumerable().Except(dt1.AsEnumerable());
for Except you have to add using System.Linq
Namespace.
you have to also assigned a Rang for dt1
dt1.Columns.AddRange(new DataColumn[6] { new DataColumn("ID", typeof(int)),
new DataColumn("Acount", typeof(string)),
new DataColumn("Name", typeof(string)),
new DataColumn("Quarter", typeof(string)),
new DataColumn("FY", typeof(int)),
new DataColumn("Income_percent", typeof(int))});
Upvotes: 0
Reputation: 5264
you can use this
public DataTable getLinq(DataTable dt1, DataTable dt2)
{
DataTable dtMerged =
(from a in dt1.AsEnumerable()
join b in dt2.AsEnumerable()
on
a["Query"].ToString() equals b["Query"].ToString()
into g
where g.Count() > 0
select a).CopyToDataTable();
return dtMerged;
}
For more Info see here
Upvotes: 0