score:10

Accepted answer

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

score:1

Not sure how your is but RouteLinqs is defined, but perhaps you are looking to select a specific object from the class RouteLinqs.

var res = (from p in aspdb.RouteLinqs
                   orderby p.RouteId descending
                   select p.SomeProperty).Take(1);

In this case p is a single item of RouteLinqs and p.SomeProperty should be your int value.

score:2

This code should work:

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

score:3

Looks like you're selecting the max route id, so why not just do:

route.Id = aspdb.RouteLinqs.Max(x => x.RouteId);

score:0

First make linq :

IQueryable<int> query = (from p in aspdb.RouteLinqs
                           orderby p.RouteId descending
                           select p.Id);

Than run:

 int result = query.FirstOrDefault();

In 1 command:

int result = (from p in aspdb.RouteLinqs
                           orderby p.RouteId descending
                           select p.Id).FirstOrDefault();

Related Articles