Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query syntax and extension methods

Tags:

c#

linq

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?

like image 955
Darcara Avatar asked Dec 04 '22 19:12

Darcara


1 Answers

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.

like image 160
xanatos Avatar answered Dec 23 '22 15:12

xanatos