如果在执行查询后没有任何元素,则我正在尝试返回空值,我使用的是DefaultIfEmpty()方法,但它并不阻止抛出该异常:
引发的异常:“System.InvalidOperationException”在System.Data.DataSetExtensions.dll中 附加信息:源包含一个为null的DataRow引用。
我的代码:
DataTable filtered = dt.AsEnumerable()
.Where(x => x.Field<string>("SLA") == "Valid"
&& x.Field<string>("Status") == "Finished")
.Select(y => y)
.DefaultIfEmpty()
.CopyToDataTable();
如何将空值返回到filtered
数据表?
发布于 2017-09-03 12:15:06
DefaultIfEmpty
返回带有默认值‘’项的初始化集合,而不是按需要返回null
:
如果序列为空,则返回指定序列的元素或单例集合中类型参数的默认值。
相反,您可以做的是检查项目的数量:
DataTable filtered = dt.AsEnumerable()
.Where(x => x.Field<string>("SLA") == "Valid"
&& x.Field<string>("Status") == "Finished")
.Select(y => y)
.CopyToDataTable();
if(filtered.Rows.Count == 0)
{
filtered = null;
}
或更好:
var collection = dt.AsEnumerable()
.Where(x => x.Field<string>("SLA") == "Valid"
&& x.Field<string>("Status") == "Finished")
.Select(y => y);
DataTable filtered = collection.Any() ? collection.CopyToDataTable() : null;
https://stackoverflow.com/questions/46023291
复制相似问题