converting LINQ query result to int

c#, linq, type-conversion

Solution

that is because `res.FirstOrDefault()` returns a `RouteLinqs` type object, because you are using `select p` , you may select a field using `select p.FieldName`, where FieldName is the property you require for conversion, which is probably `RouteId`

You may want to query the particular field in your linq query.

var res = (from p in aspdb.RouteLinqs
                       orderby p.RouteId descending
                       select p.RouteId).Take(1); //p.RouteID or any field you want. 

Or with your current query, you may do:

 route.Id =Convert.ToInt32(res.FirstOrDefault().RouteID);

Problem

I've written a LINQ query that should return an int value. but I'm not able to convert this value to int and an exception occured: Unable to cast object of type 'QuickRoutes.DAL.RouteLinq' to type 'System.IConvertible'. this is my LINQ : ``` var res = (from p in aspdb.RouteLinqs orderby p.RouteId descending select p).Take(1); ``` and the exception occures here: ``` route.Id =Convert.ToInt32(res.FirstOrDefault()); ``` how can I solve this problem?

Original source