BattlFrog
BattlFrog

Reputation: 3397

Convert single LINQ value to string

I am pulling a single value from the db using LINQ:

    public string GetPoliceDepartmentName(int id)
    {
        var PoliceDepartmentName = from p in db.PoliceDepartmentList
                                   join l in db.TrespassOrder on p.PoliceDeptId equals l.PoliceDepartmentId
                                   where l.IncidentId == id
                                   select p.DepartmentName.Single();
        return PoliceDepartmentName.ToString();
    }

The method runs, but instead of returning the expected "Boston PD", it returns System.Data.Objects.ObjectQuery`1[System.Char]

I'm not sure why my method isn't converting from queriable to string. I will keep researching, but a hint would be nice at this point.

Upvotes: 1

Views: 358

Answers (2)

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

You're calling Single on string, which is IEnumerable<char>, so you'll get first (and only) char from string. That's probably not what you're looking for.

With proper brackets, you won't need ToString call at all, because PoliceDepartmentName will be types as string automatically.

var PoliceDepartmentName = (from p in db.PoliceDepartmentList
                           join l in db.TrespassOrder on p.PoliceDeptId equals l.PoliceDepartmentId
                           where l.IncidentId == id
                           select p.DepartmentName).Single();
return PoliceDepartmentName;

Upvotes: 6

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

You need brackets :

(from p in db.PoliceDepartmentList
 join l in db.TrespassOrder on p.PoliceDeptId equals l.PoliceDepartmentId
 where l.IncidentId == id
 select p.DepartmentName).Single();

Upvotes: 3

Related Questions