如何修复 "The source contains no DataRows"?
How to fix "The source contains no DataRows"?
这里我想从两个数据表中找到匹配的记录。代码是
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;
}
当数据表不包含匹配记录时它给出 "The source contains no DataRows"...
如何改正..请给出您的建议
两种方式:
- 在调用
CopyToDataTable
之前检查它是否包含带有 Enumerable.Any
的行
- 使用
dtfff.Clone
创建一个与源具有相同架构的空 DataTable table 并使用循环从 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;
我更喜欢第二种方法,因为它只需要执行一次查询。
这里我想从两个数据表中找到匹配的记录。代码是
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;
}
当数据表不包含匹配记录时它给出 "The source contains no DataRows"... 如何改正..请给出您的建议
两种方式:
- 在调用
CopyToDataTable
之前检查它是否包含带有 - 使用
dtfff.Clone
创建一个与源具有相同架构的空 DataTable table 并使用循环从 LINQ 查询中填充它。
Enumerable.Any
的行
第一种方法:
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;
我更喜欢第二种方法,因为它只需要执行一次查询。