Tutorial :Anonymous types query or normal query in LINQ


var emps = from x in DB               where x.ID = 100              select x;    var emp1 = from x1 in DB             where x1.ID = 100              select new { x };  

What is difference between these two queries.

If we use anonymous-types is the performance will be increased or any other differences also there?


There is a big diffrence in those two queries. First returns collection of your entity, the second returns collection of anonymous-type which has a member called 'x' containing your entity.

Access to emps:


Access to emp1:


The first way is correct and natural, second is strange and in my opinion not really what you want to achive.

Also it's not true, that using anonymous type here will increase performance. The object representing entity have to be build anyway, but this time you are getting it in less friendly form.


Most performance considerations are likely to be in terms of the SQL generated - and that shouldn't change here. (You can check, of course, but I'd be staggered if it made a difference.)

It takes a little bit more effort to create an instance of an anonymous type than not to, of course. I can't see any reason why using an anonymous type here would make it perform better - I'd expect it to perform very marginally worse, but not actually noticeably so.

More importantly, I can't see how the latter adds anything other than an unnecessary additional layer of indirection. It will make your code marginally less clear, for no benefit. Anonymous types are great when you want to bring together separate values - or query just a subset of the columns in a table - but single-property anonymous types are rarely useful.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »