Anonymous query type or regular 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 the difference between these two queries.

If we use anonymous types, will performance improve or will any other differences also exist?

+4
c # linq anonymous-types
source share
2 answers

There is a big difference in these two queries. First returns a collection of your entity, the second returns a collection of an anonymous type that has a member called "x" containing your entity.

Access to emps:

 emps.First().SomeMember 

Access emp1:

 emp1.First().x.SomeMember 

The first method is correct and natural, the second is strange and, in my opinion, not quite what you want to achieve.

And it's not true that using an anonymous type here will improve performance. The object representing the object should be built anyway, but this time you get it in a less friendly form.

+4
source share

Most performance considerations are likely to be in terms of the generated SQL - and this should not change here. (Of course, you can check, but I would stagger if that mattered.)

It takes a little more effort to create an instance of an anonymous type, and not, of course. I see no reason why using an anonymous type would improve its performance - I expect it to act very little, but it's not really noticeable.

More importantly, I do not see how the latter adds anything but an unnecessary additional layer of indirection. This will make your code slightly less clear without any benefit. Anonymous types are great when you want to combine individual values ​​- or query only a subset of columns in a table, but anonymous types with one property are rarely useful.

+3
source share

All Articles