【问题标题】:How to fix "The source contains no DataRows"?如何修复“源不包含数据行”?
【发布时间】:2015-11-25 14:47:57
【问题描述】:

在这里我想从两个数据表中找到匹配的记录。代码是

public DataTable textfiltering(DataTable dtfff, DataTable dtff)
{
   DataTable ds = (DataTable)Session["maintxt"];
   DataTable dts = (DataTable)Session["sectxt"];
   dtfff = ds;
   dtff = dts;     

   DataTable dtMerged = (from a in dtfff.AsEnumerable()
                          join b in dtff.AsEnumerable()
                          on a["contacts"].ToString() equals b["contacts"].ToString()
                          into g                                 
                          where g.Count()>0                             
                          select a).CopyToDataTable();
           return dtMerged;    

}

当数据表不包含匹配记录时,它会给出“源不包含 DataRows”... 如何纠正它..请提出您的建议

【问题讨论】:

  • 旁注:你应该明确地重新考虑你的变量命名。 dsdtsdtfffdtff 描述性不强。

标签: c# datatable


【解决方案1】:

两种方式:

  1. 在调用CopyToDataTable 之前检查它是否包含带有Enumerable.Any 的行
  2. 使用dtfff.Clone 创建一个与源表具有相同架构的空DataTable,并使用循环从LINQ 查询中填充它。

第一种方法:

var rows = from a in dtfff.AsEnumerable()
           join b in dtff.AsEnumerable()
           on a["contacts"].ToString() equals b["contacts"].ToString()
           into g
           where g.Count() > 0
           select a;
DataTable merged;
if (rows.Any())
   merged = rows.CopyToDataTable();
else
    merged = dtfff.Clone();
return merged;

第二种方法:

DataTable merged = dtfff.Clone();
foreach (DataRow sourceRow in rows)
{
   merged.ImportRow(sourceRow);  // or add all fields manually
}
return merged;

我更喜欢第二种方法,因为它只需要执行一次查询。

【讨论】:

  • 你能给我举个例子吗?
猜你喜欢
  • 1970-01-01
  • 2010-10-16
  • 2019-09-17
  • 1970-01-01
  • 2020-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-29
相关资源
最近更新 更多