I usually prefer the extension methods, because they i find them easier to read, but after seeing the answer by Erno to this question I was wondering how the minimum query would look with only extension methods used?
And more generally, are there queries that you can create in one form but not the other, or are both approaches equivalent?
Taken from ILSpy:
This
var minimum = (from p1 in differenceList
from p2 in differenceList
let distance = Math.Abs(p1.X - p2.X)
where !object.ReferenceEquals(p1, p2)
orderby distance
select new { Point1 = p1, Point2 = p2, Distance = distance }).First();
is (with a little cleaning) and with comments
var minimum = differenceList
// The two from
.SelectMany(
p1 => differenceList,
(p1, p2) =>
new {
p1 = p1,
p2 = p2
})
// The let
.Select(q =>
new{
q = q,
distance = Math.Abs(q.p1.X - q.p2.X)
})
// The where
.Where(r => !object.ReferenceEquals(r.q.p1, r.q.p2))
// The orderby
.OrderBy(r => r.distance)
// The final select
.Select(r => new
{
Point1 = r.q.p1,
Point2 = r.q.p2,
Distance = r.distance
})
// The First
.First();
I have to tell the truth, the only thing I didn't know how to do "by hand" was the two from
. I suspected it was a SelectMany
, but it would have taken me at least 30 minutes to crack it. If you are interested, in ILSpy Options->Decompiler and deactivate "Decompile query expressions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With