views:

66

answers:

2
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?

+2  A: 

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.

Jon Skeet
I think that he just gave a simple example, stripped from most of the complexity. I can see use case where anonymous results would be usefull, especially when you want to return a collection of n-tuples. it removes the painstacking job of declaring "select new Tuple<thing, thing, thing, thing, thing, thing>(myThing, myThing,myThing,myThing,myThing,myThing)"...
Aurélien Ribon
Sure.. anonymous-types was not invented for nothig and there is variety of possible usages which are good. Still I think, that he meant to ask if presented example makes an performance diffrence.
ŁukaszW.pl
@Aurélien: And that's why I've explicitly said where anonymous types are useful. But they're *not* useful in the only example presented, and they don't give a performance benefit either.
Jon Skeet
+4  A: 

Hi!

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:

emps.First().SomeMember

Access to emp1:

emp1.First().x.SomeMember

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.

ŁukaszW.pl