简体   繁体   中英

What is the difference between these two statements (asp.net/c#/entity framework)

IEnumerable<Department> myQuery = (from D in myContext.Departments orderby D.DeptName select D);

var myQuery = (from D in myContext.Departments orderby D.DeptName select D);

What is the difference between these two statements above? In my little asp.net/C#/ EF4.0 app I can write them either way, and as far as how I want to use them, they both work, but there has to be a reason why I would choose one over the other?

The second one is shorter (assuming type of D is Department ).

(actually, the return type of the query may be something other than IEnumerable , like IQueryable but the point is, the type will be statically inferred from the right hand side of the assignment operator instead of being explicitly mentioned in code).

(from D in myContext.Departments orderby D.DeptName select D);

returns an object of type IQueriable<Department> which in turn implements IEnumerable<Department>

while you use the var keyword in here the compiler replace it with IQueriable<Department>

I believe in the 2nd case the type of myQuery is an IQueryable<Department> rather than IEnumerable . If you don't need anything specific to an IQueryable that you can't do with an IEnumerable then they behave the same.

The var keyword is just for convenience when the compiler can figure out the type without spelling it out. So instead of

MyReallyLongGenericClassName<SomeOtherType> myObject = new MyReallyLongGenericClassName<SomeOtherType>();

You can just write var myObject = new MyReallyLongGenericClassName<SomeOtherType>();

With var the compiler infers the type of myQuery. It would probably endup being an IQueryable<Department> rather than an IEnumerable<Department> .

The only difference here is that you're not declaring yourself the type of myQuery . You're taking advantage of a feature named Type Inference . Indeed the type returned will be IQueryable<Department> where the first statment explicitly types the variable as IEnumerable .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM