问题描述
我已经按照TblUserMessages
LINQ to SQL查询表达式
I have following LINQ to SQL query expression
from msg in TblUserMessages
join user in Aspnet_Users on msg.FromUserID equals user.UserId
select new {
msg.FromUserID,
msg.ToUserID,
msg.MessageLocationID,
msg.MessageID,
user.UserName
}
和下面的LINQ方法表达式:
And following LINQ method expression:
TblUserMessages
.Join (
Aspnet_Users,
msg => msg.FromUserID,
user => user.UserId,
(msg, user) =>
new
{
FromUserID = msg.FromUserID,
ToUserID = msg.ToUserID,
MessageLocationID = msg.MessageLocationID,
MessageID = msg.MessageID,
UserName = user.UserName
}
)
这两个返回相同的结果集。这是如
Both of these return same result set. Which is e.g. :
82522f05-2650-466a-a430-72e6c9fb68b7
6b2a174a-8141-43d2-b3ad-5b199bcbfcae
1
1
waheed
哪一个是更好地使用。在第一个
一个或第二个
之一。
Which one is better to use. The FIRST
one or the SECOND
one.
谢谢
推荐答案
他们是等价的。他们不只是返回的结果集相同 - 它们编译为相同的代码
They are equivalent. They don't just return the same result set - they compile to the same code.
使用查询表达式或点符号为根据可读性个别情况。对于加入,我觉得点符号相当麻烦 - 但我使用它的情况下我只有一个或两个条款(通常在哪里/选择)。即使有两个子句(通常是在那里的和的选择)我找到点符号,如果不错的话,你无论如何需要使用它。比如,我喜欢:
Use query expressions or dot notation for individual cases depending on readability. For joins, I find the dot notation quite cumbersome - but I use it for situations where I only have one or two clauses (usually where/select). Even with two clauses (usually where and select) I find dot notation nice if you then need to use it anyway. For example, I like:
var query = people.Where(person => person.Age > 18)
.Select(person => person.Name)
.Skip(100)
.Take(10);
在
over
var query = (from person in people
where person.Age > 18
select person.Name)
.Skip(100)
.Take(10);
有关更复杂的查询(如连接)我可能只是分隔两个:
For more complicated queries (e.g. joins) I'd probably just separate the two:
var baseQuery = from person in people
where person.Age > 18
join company on person.CompanyId equals company.CompanyId
select new { person.Name, company.Name };
var fullQuery = baseQuery.Skip(100)
.Take(10);
我只是觉得这种分离使得它更容易阅读。
I just find this separation makes it easier to read.
我相信这是真正有用的开发人员理解什么查询表达式至少做基础 - 事实上,他们基本上翻译成点符号,而语言本身不知道什么LINQ到对象,LINQ to SQL的等;它只是下面的一个合适的模式的情况下。这是设计的一大位,这意味着查询表达式只影响语言规范的一个点点。
I believe it's really useful for developers to understand at least the basics of what query expressions do - the fact that they're basically translations into dot notation, and that the language itself doesn't know anything about LINQ to Objects, LINQ to SQL etc; it's just a case of following an appropriate pattern. It's a great bit of design, which means query expressions only affect one little bit of the language specification.
这篇关于哪一个是更好的lambda表达式或的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!