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
}
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.
Thanks
There's no better one. Use what you like. I would, in this case, go with the 'query' syntax, since I think it's more readable than the second one. Moreover, since we're writing SQL anyway, I think this syntax resembles it better. But I'm sure others will disagree and tend to choose the lamda version.
I usually go with the latter syntax btw, since I prefer the lambda syntax cause it is often more readable and shorter.
See also this SO question.
I'd always go for the more readable option and in this case I think its the LINQ snippet.
Whichever you find easier to read.
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:
over
For more complicated queries (e.g. joins) I'd probably just separate the two:
I just find this separation makes it easier to read.
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.
Both will perform equally well, but I will prefer the first since it's easier to read and understand.
"write your code, then measure it to find out what to refactor." Have you measured both? Better is subjective.
Are you finding a problem with either one that is making you want to choose one over the other?