-3

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Laziale
  • 7,965
  • 46
  • 146
  • 262
  • Both are equally good. Query syntax will get translated to method syntax but that's a negligible performance impact. – Jeroen Vannevel Oct 08 '14 at 06:58
  • 1
    @jmcilhinney I'm wondering how to do the ON part and also WHERE join on the same table. Thanks for your help. – Laziale Oct 08 '14 at 07:01
  • 1
    What do you not understand about the examples you found when you searched? This question comes across as "I couldn't be bothered trying, you do it for me". If you have no idea then you can't really have looked too hard. If you do have some idea, what did you try and what happened when you tried it? – jmcilhinney Oct 08 '14 at 07:04
  • 1
    Don't let anybody tell yo that you *should* use method syntax. That's nonsense. Esp. with joins, groupings and SelectMany (`from - from` in query syntax), query syntax is much more succinct. We want maintainable code, don't we? – Gert Arnold Oct 08 '14 at 07:15
  • 1
    Once you are familliar with method syntax using lambda expressions they are just as good as the query syntax. People with SQL background might find the query syntax easier to understand because they are already used to declarative programming. But that's basically just a personal preference. If you are required to use the method syntax then you might first want to learn the syntax of the 'join' method as it is used quite often. And you might want to learn the basics about functional programming as lambda expressions are just like that. – Frank Oct 08 '14 at 08:31
  • I personally like query syntax. Easier on my eyes. But I do find my self using method syntax the less complex queries. – RayLoveless Oct 19 '17 at 17:48

1 Answers1

1
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();
Giannis Paraskevopoulos
  • 18,261
  • 1
  • 49
  • 69