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