源不包含DataRows

DataTable dt = ds.Tables[4].AsEnumerable() .Where(x => ((DateTime)x["EndDate"]).Date >= DateTime.Now.Date) .CopyToDataTable(); 

ds.Tables[4]有行,但它抛出exception

“源不包含DataRows。”

知道如何处理或摆脱这种exception吗?

ds.Tables[4]可能,但你的linq查询的结果可能不会,这可能是抛出exception的地方。 拆分方法链接以使用临时参数,这样您就可以确定错误发生的位置。 它还可以帮助您在调用CopyToDataTable()之前检查现有行并避免所述exception。

就像是

 DataTable dt = null; var rows = ds.Tables[4].AsEnumerable() .Where(x => ((DateTime)x["EndDate"]).Date >= DateTime.Now.Date); if (rows.Any()) dt = rows.CopyToDataTable(); 

另一种选择是在DataTable上使用ImportRow函数

 DataTable dt = ds.Tables[4].Clone(); var rows = ds.Tables[4].AsEnumerable() .Where(x => ((DateTime)x["EndDate"]).Date >= DateTime.Now.Date); foreach (var row in rows) dt.ImportRow(row); 

简单地分成两行

 var rowSources = ds.Tables[4].AsEnumerable() .Where(x => ((DateTime)x["EndDate"]).Date >= DateTime.Now.Date); if(rowSources.Any()) { DataTable dt = rowSources.CopyToDataTable(); ... code that deals with the datatable object } else { ... error message ? } 

这允许检查结果是否包含任何DataRow,如果是,则可以调用CopyToDataTable方法。