LINQ中的匿名类型查询或普通查询 [英] Anonymous types query or normal query in LINQ

查看:145
本文介绍了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?

推荐答案

这两个查询存在很大差异.第一个返回您实体的集合,第二个返回匿名类型的集合,其中匿名类型包含包含您的实体的成员"x".

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.

访问emps:

emps.First().SomeMember

访问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.

这篇关于LINQ中的匿名类型查询或普通查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆