开发者

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

开发者 https://www.devze.com 2022-12-31 20:20 出处:网络
IEnumerable<Department> myQuery = (from D in myContext.Departments orderby D.DeptName select D);
IEnumerable<Department> myQuery = (from D in myContext.Departments orderby D.DeptName select D);

var myQuery = (from D in myContext开发者_如何学Go.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?


(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>


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


syntactic convenience


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消