Search code examples
c#linqwebmethod

check whether LINQ query returns rows


I need to check whether a query returns rows and if it does, change it to a string, but if it doesn't, return "In Progress". I thought the below code would work but this is always true:

if (System.Linq.Enumerable.Count(columns) == 0)<--- always true but it shouldn't be

And when there isn't a row returned to columns I get the following error in my jQuery Ajax: "The cast to value type \u0027Int32\u0027 failed because the materialized value is null. Either the result type\u0027s generic parameter or the query must use a nullable type."

Here's my 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)
        }

    }

Solution

  • You first check for Count == 0, doesn't sound right, I guess you need the opposite check. You should use Any or Count() > 0 check, Like:

    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)
    }
    

    You have to convert your List to string, in order for your method to return a string.