Search code examples
c#linqlinq-to-sqllinq-method-syntax

linq convert query syntax to method syntax


How can I convert this query syntax to method syntax in linq:

             return (from x in db.Table1
                    join y in db.Table1 on x.ID equals y.ID - 1
                    where Convert.ToInt32(y.ID) >= Convert.ToInt32(x.ID)
                    orderby x.Name
                    select x).Distinct();

Which approach is better? I like this query approach better but I was asked to work with method syntax which looks too bloated to me.


Solution

  • var results = db.Table1.Join
        (
            db.Table1,
            x=>x.ID,
            x=>x.ID - 1,
            (x,y)=>new{OuterTable = x, xid = x.ID, yid = y.ID}
        )
        .Where(x=>Convert.ToInt32(x.yid ) >= Convert.ToInt32(x.xid))
        .Select(x=>x.OuterTable)
        .OrderBy(x=>x.Name)
        .Distinct();