我有两个数据表,我想从第一个表中选择第二个表中不存在的行
例如:<>之前表一个id列1 data12 data23 data34 data4表Bid列1 data103 data30之前我想要的结果是:
<>之前表Cid列2 data24 data4您可以使用Linq,特别是Enumerable.Except
帮助查找TableA中没有在TableB中的id:
var idsNotInB = TableA.AsEnumerable().Select(r => r.Field<int>("id"))
.Except(TableB.AsEnumerable().Select(r => r.Field<int>("id")));
DataTable TableC = (from row in TableA.AsEnumerable()
join id in idsNotInB
on row.Field<int>("id") equals id
select row).CopyToDataTable();
您也可以使用Where
,但它将效率较低:
DataTable TableC = TableA.AsEnumerable()
.Where(ra => !TableB.AsEnumerable()
.Any(rb => rb.Field<int>("id") == ra.Field<int>("id")))
.CopyToDataTable();
我得到了一个没有LINQ的解决方案:
public DataTable CompareDataTables(DataTable first, DataTable second)
{
first.TableName = "FirstTable";
second.TableName = "SecondTable";
//Create Empty Table
DataTable table = new DataTable("Difference");
try
{
//Must use a Dataset to make use of a DataRelation object
using (DataSet ds = new DataSet())
{
//Add tables
ds.Tables.AddRange(new DataTable[] { first.Copy(), second.Copy() });
//Get Columns for DataRelation
DataColumn[] firstcolumns = new DataColumn[ds.Tables[0].Columns.Count];
for (int i = 0; i < firstcolumns.Length; i++)
{
firstcolumns[i] = ds.Tables[0].Columns[i];
}
DataColumn[] secondcolumns = new DataColumn[ds.Tables[1].Columns.Count];
for (int i = 0; i < secondcolumns.Length; i++)
{
secondcolumns[i] = ds.Tables[1].Columns[i];
}
//Create DataRelation
DataRelation r = new DataRelation(string.Empty, firstcolumns, secondcolumns, false);
ds.Relations.Add(r);
//Create columns for return table
for (int i = 0; i < first.Columns.Count; i++)
{
table.Columns.Add(first.Columns[i].ColumnName, first.Columns[i].DataType);
}
//If First Row not in Second, Add to return table.
table.BeginLoadData();
foreach (DataRow parentrow in ds.Tables[0].Rows)
{
DataRow[] childrows = parentrow.GetChildRows(r);
if (childrows == null || childrows.Length == 0)
table.LoadDataRow(parentrow.ItemArray, true);
}
table.EndLoadData();
}
}
}
更多信息请访问http://microsoftdotnetsolutions.blogspot.in/2012/12/compare-two-datatables.html
您可以使用Linq Enumerable。除了方法函数来获取两个数据表之间的差异,这里我使用firstDt和secondDt,记住两个Dt具有相同的结构。
var EntriesNotInB = firstDt.AsEnumerable().Select(r => r.Field<string>("abc")).Except(secondDt.AsEnumerable().Select(r => r.Field<string>("abc")));
if (EntriesNotInB.Count() > 0)
{
DataTable dt = (from row in firstDt.AsEnumerable()join id in EntriesNotInB on row.Field<string>("abc") equals id select row).CopyToDataTable();
foreach (DataRow row in dt.Rows)
{
/////Place your code to manipulate on datatable Rows
}
}
阅读更多关于Enumerable的信息。除Method外,请访问http://msdn.microsoft.com/en-us/library/system.linq.enumerable.except(v=vs.110).aspx
及其完成!!!!编码快乐……