【发布时间】:2014-02-15 17:28:00
【问题描述】:
我需要检查查询是否返回行,如果返回,则将其更改为字符串,但如果没有,则返回“In Progress”。我认为下面的代码会起作用,但这总是正确的:
if (System.Linq.Enumerable.Count(columns) == 0)<--- always true but it shouldn't be
当没有行返回到列时,我的 jQuery Ajax 中出现以下错误: “转换为值类型 \u0027Int32\u0027 失败,因为具体化值为 null。结果类型\u0027s 泛型参数或查询必须使用可为空的类型。”
这是我的 WebMethod:
using (dbPSREntities5 myEntities = new dbPSREntities5())
{
var thisId = myEntities.tbBreadCrumbs.Where(x => x.ProjectID == projectID && x.StatusID == statusID).Max(x => x.BreadCrumbID);
var columns = myEntities.tbBreadCrumbs
.Where(x => x.BreadCrumbID == thisId)
.Select(x => x.CreateDateTime)
.ToList();
if (System.Linq.Enumerable.Count(columns) == 0)
{
var formattedList = columns
.Select(d => null != d
? d.Value.ToString("MMM dd, yyyy")
: string.Empty) // this is just one example to handle null
.ToList();
return formattedList;<-- return this if there is a BreadCrumbID (columns would have a row)
}
else
{
return "In Progress";<--- there was no BreadCrumbID (columns would have 0 rows)
}
}
【问题讨论】:
-
你试过
if(!columns.Any()) { ... } -
其实正如别人指出的,他的情况是倒退的。应该是 columns.Any(),你第一次做对了 :)