比较DataTable中的行

时间:2017-11-30 10:06:09

标签: c#

我有2个DataTable,如下所示:

YesterdaysTable  
AAA  
BBB  
CCC  
DDD  
EEE  
FFF  
GGG  
HHH  
III  
JJJ  

TodaysTable  
AAA  
BBB  
DDD  
FFF  
GGG  
HHH  
III  
JJJ  

如您所见,TodaysTable不包含CCC& EEE。当我尝试找出差异时,让我知道YesterdaysTableTodaysTable中使用以下代码时不存在的内容,我收到错误:

  

InvalidOperationException:源不包含DataRows

但我的来源中行:

DataTable dtSource = new DataTable();
dtSource = yesterdaysTable.AsEnumerable().Except(todaysTable.AsEnumerable()).CopyToDataTable();

var difference = yesterdaysTable.AsEnumerable().Select(r => r.Field<string>("Apps")).Except(todaysTable.AsEnumerable().Select(r => r.Field<string>("Apps")));

if (difference.Any())
{
    DataTable Table3 = (from row in todaysTable.AsEnumerable()
                        join app in difference on row.Field<string>("Apps") equals app
                        select row).CopyToDataTable();
}

当我使用类似代码时出现同样的错误:

var appsNotInB = yesterdaysTable.AsEnumerable().Select(r => r.Field<string>("Apps"))
        .Except(todaysTable.AsEnumerable().Select(r => r.Field<string>("Apps")));

var TableC = (from row in yesterdaysTable.AsEnumerable()
              join id in appsNotInB on row.Field<string>("Apps") equals id
              select row).CopyToDataTable();

我试着编写一个嵌套的for循环试图将差异放入List<string>对象,但无济于事:

for (int i = 0; i < yesterdaysTable.Rows.Count; i++)
{
    for (int j = 0; j < todaysTable.Rows.Count; j++)
    {
        if (yesterdaysTable.Rows[i]["Apps"].ToString() != todaysTable.Rows[j]["Apps"].ToString())
        {
            //lstNoMatch.Add(yesterdaysTable.Rows[i]["Apps"].ToString());
            lstNoMatch.Add(todaysTable.Rows[j]["Apps"].ToString());
        }
    }
}

我尝试了一些不同的解决方案,但没有任何工作,我也不希望帖子不必要地长。我已经走到了尽头:(

有什么建议吗?

0 个答案:

没有答案