How to do a join in linq to sql with method syntax?

chobo2 picture chobo2 · Jul 10, 2010 · Viewed 120.2k times · Source

I have seen lots of examples in LINQ to SQL examples on how to do a join in query syntax but I am wondering how to do it with method syntax? For example how might I do the following

var result = from sc in enumerableOfSomeClass
             join soc in enumerableOfSomeOtherClass
             on sc.Property1 equals soc.Property2
             select new { SomeClass = sc, SomeOtherClass = soc }

with a .Join()? Can anyone illustrate or provide another simple example?

Answer

Justin Niessner picture Justin Niessner · Jul 10, 2010
var result = from sc in enumerableOfSomeClass
             join soc in enumerableOfSomeOtherClass
             on sc.Property1 equals soc.Property2
             select new { SomeClass = sc, SomeOtherClass = soc };

Would be equivalent to:

var result = enumerableOfSomeClass
    .Join(enumerableOfSomeOtherClass,
          sc => sc.Property1,
          soc => soc.Property2,
          (sc, soc) => new
                       {
                           SomeClass = sc,
                           SomeOtherClass = soc
                       });

As you can see, when it comes to joins, query syntax is usually much more readable than lambda syntax.