DataTable 1 :-
Caption |ID
------------
Caption1|1
Caption2|2
Caption3|3
DataTable 2 :-
Name |ID
------------
Name1|1
Name2|2
I want to compare the above two data tables and fetch the value "Caption3" so I can display a message on screen that "No name for "Caption3" exist!"
I have tried merging as follows but it's fetching DataTable 2 as it is in dtTemp !
datatable1.Merge( datatable2);
DataTable dtTemp = datatable2.GetChanges();
Also tried the logic as follows that removes rows with same IDs in both tables and updates datatable2's rows and only the ones that don't have duplicated IDs will remain...This didn't work either.
:(
if (datatable2.Rows.Count != datatable1.Rows.Count)
{
if (datatable2.Rows.Count != 0)
{
for (int k = 0; k < datatable2.Rows.Count; k++)
{
for (int j = 0; j < datatable1.Rows.Count; j++)
{
if (datatable1.Rows[j]["ID"].ToString() == datatable1.Rows[k]["ID"].ToString())
{
datatable1.Rows.Remove(datatable1.Rows[j]);
datatable1.AcceptChanges();
}
// string test = datatable1.Rows[0]["ID"].ToString();
}
}
}
How do I fetch those "CAPTIONS" whose corresponding "NAMES" do not exist?? Please help thanks.
Note:- Rows in both datatables will vary based on some logic. What I want is to fetch that CAPTION from datatable1 who's KCID doesn't exist in datatable2.
edit:- How else do I loop through datatable1's rows and check which ID(from datatable1) doesn't exist in datatable2 and then print those captions on 开发者_开发技巧my page?
@CodeInChaos:: I have not worked with Linq-To-Objects at all so not able to understand your code :/
Is there any other way to loop through that datatable and fetch "caption " who's correcponding "Name" doesn't exist in the datatable2??
Someone please help me out with this. I am clueless how else how else to loop through the datatable rows if not like above.
Note that this code uses Linq-To-Objects and thus needs to whole tables in your application. There might be a better solution which works on the database server. But unlike your code it's at linear in the size of the tables.
HashSet<int> ids2=new HashSet<int>(Table2.Select(e=>e.ID));
var entriesOnlyInTable1=Table1.Where(e=>!ids2.Contains(e.ID));
IEnumerable<string> captionsOnlyInTable1=onlyInTable1.Select(e=>e.Caption);
Without LINQ:
HashSet<int> ids2=new HashSet<int>();
foreach(var e in Table2)
{
ids2.Add(e.ID);
}
List<string> captionsOnlyInTable1=new List<string>();
foreach(var e in Table1)
{
if(!ids2.Contains(e.ID))
captionsOnlyInTable1.Add(e.Caption);
}
精彩评论