tags:

views:

73

answers:

4

I need help in turning this linq expression into a linq statment. SampleData.Publishers and SampleData.Books are simple collections that I have from the Linq in Action book.

Here is the expression

var pubBooks =
            from pub in SampleData.Publishers
            join book in SampleData.Books on pub.Name equals book.Publisher.Name into pubbks
            select new {
                Publisher = pub.Name,
                Books =
                    from b in pubbks
                    select b.Title
            };

Here is what I have so far, but I can't seem to get the books collection defined in the anonymous type. Thanks for your time.

var pubBooks = SampleData.Publishers.Join(SampleData.Books, pub => pub.Name, book => book.Publisher.Name, (pub, book) => new {
            Publisher=pub.Name,
            Books=??????
        });
+3  A: 

Really easy way to do that is to use Reflector. When you analyze your code you will see statement, not an expression.

empi
+3  A: 

Another good way to transform this is to use LinqPad.

Carles
+2  A: 

You can use GroupJoin.

I didn't test this but it could look like this:

var pubBooks = SampleData.Publishers.GroupJoin(SampleData.Books, pub => pub.Name, book => book.Publisher.Name, (pub, bookColl) => new {
            Publisher = pub.Name,
            Books = bookColl.Select(b => b.Title)
        });
bruno conde
A: 

Resharper gave me this:

var pubBooks =
            SampleData.Publishers.GroupJoin(
                SampleData.Books,
                pub => pub.Name,
                book => book.Publisher.Name,
                (pub, pubbks) => new
                                     {
                                         Publisher = pub.Name,
                                         Books =
                                     from b in pubbks
                                     select b.Title
                                     });
rohancragg
I take no credit for this :-)Someone should write an online LINQ-expression to statement conversion widget...
rohancragg
p.s. I didn't test it, obviously.
rohancragg