var query = (from RESTAURANT in db.RESTAURANTs
where RESTAURANT.REST_ID == RestID
select new { name = RESTAURANT.name});
How to cast the query
instead of var
?
thank you.
Add more information, i want to make the following possible. Is it possible?
As discussed, the Cast operator in LINQ will convert the same type of elements present in one list to another new type. In case if the collection contains a different type of elements and if we try to convert that collection, we will get an error like “ Unable to cast object of type ‘System.Int32’ to type ‘System.String’ ”.
These countries are of type Object, and by using Cast operator, we are converting ArrayList object to string type object. Following is the result of the LINQ Cast conversion operator example. As discussed, the Cast operator in LINQ will convert the same type of elements present in one list to another new type.
Dim result As IEnumerable(Of String) = obj.Cast(Of String) () If you observe the above syntax, we are typecasting the “ result ” collection to a new string object. Following is the example of casting or converting list/collection items into the specified data type of new collection.
Note that one uses OfType<T> (), which you were using. This will filter the results and return only the items of the specified type. The second query implicitly uses Cast<T> (), which casts the results into the specified type. If any item cannot be cast, an exception is thrown.
Mouse-over the var
and your compiler will tell you what type it substitutes for it.
If you want to use that type explicitly instead, you will need to insert it instead of var
. It won't change anything for the compiler though.
Your query currently allocates an anonymous type using select new { }
, which requires you to use var
. If you want allocate a known type, add it to your select
clause:
IEnumerable<SomeType> query =
from RESTAURANT in db.RESTAURANTs
where RESTAURANT.REST_ID == RestID
select new SomeType { Name = RESTAURANT.name } ;
public class SomeType
{
public string Name { get; set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With