检查LINQ查询是否返回行

时间:2014-01-24 16:18:40

标签: c# linq webmethod

我需要检查查询是否返回行,如果是,则将其更改为字符串,但如果不是,则返回“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)
        }

    }

5 个答案:

答案 0 :(得分:3)

您可以使用Any()

MSDN Enumerable.Any Method

答案 1 :(得分:2)

你首先检查Count == 0,听起来不对,我想你需要相反的检查。您应该使用AnyCount() > 0检查,例如:

if (columns.Any()) //Or columns.Count() > 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)
}

您必须将List转换为字符串,以便您的方法返回字符串。

答案 2 :(得分:1)

你的病情有误。计数必须大于零

答案 3 :(得分:1)

您只需要查看.Count() > 0

if (columns.Count() > 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)
        }

答案 4 :(得分:1)

使用.Any()提供的List<T>方法:

If (columns.Any())
{
    // do your bidding
} else {
    // in progress code
}

此外,您的方法有两个不同的返回签名。那不会编译。除非返回类型是对象(不推荐),否则不能返回List或字符串。

我建议返回一个空列表并检查它是否在您的UI层中为空,然后显示相应的字符串或日期值,因为它们最终都是UI中的字符串。