Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast the object from linq

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?

enter image description here

like image 937
chaintng Avatar asked Aug 20 '15 10:08

chaintng


People also ask

What is the use of cast operator in LINQ?

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’ ”.

How to convert ArrayList to string type in LINQ?

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.

How do I cast a result to a new String object?

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.

How do I cast a query to a specific type?

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.


2 Answers

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.

like image 42
nvoigt Avatar answered Sep 18 '22 05:09

nvoigt


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; }
}
like image 124
Yuval Itzchakov Avatar answered Sep 19 '22 05:09

Yuval Itzchakov