user1054922
user1054922

Reputation: 2175

Convert LINQ query syntax to method syntax w/ grouping

I've done a lot of searching, but there aren't many good examples that I could find of converting LINQ query syntax to method syntax when grouping is involved.

For example, what would this be in method syntax?

List<ChapterDTO> chapters = new List<ChapterDTO>(); // Prepopulated
List<SubChapterDTO> subChapters = new List<SubChapterDTO>(); // Prepopulated
var result = from c in chapters
             join sc in subChapters on c.ID equals sc.ChapterID
             orderby c.Number
             group sc by c.DisplayName into chapterGroup
             select new Grouping<string, SubChapterDTO>(chapterGroup.Key, chapterGroup);

I tried this, but the result is not the same:

var result = chapters.Join(subChapters, c => c.ID, sc => sc.ChapterID, (c, sc) => new { Chapter = c, SubChapter = sc })
                     .OrderBy(x => x.Chapter.Number)
                     .GroupBy(x => x.Chapter.DisplayName);

If I add this onto the end, it won't compile:

.Select(x => new Grouping<string, SubChapterDTO>(x.Key, x);

"cannot convert from 'System.Linq.IGrouping<string, <anonymous type: ChapterDTO Chapter, SubChapterDTO SubChapter>>' to 'System.Collections.Generic.IEnumerable<SubChapterDTO>'"

What piece am I missing?

Upvotes: 0

Views: 545

Answers (2)

Anton&#237;n Lejsek
Anton&#237;n Lejsek

Reputation: 6103

Just use different elementSelector in GroupBy

var result = chapters.Join(subChapters, c => c.ID, sc => sc.ChapterID, (c, sc) => new { Chapter = c, SubChapter = sc })
         .OrderBy(x => x.Chapter.Number)
         .GroupBy(x => x.Chapter.DisplayName, x => x.SubChapter)
         .Select(x => new Grouping<string, SubChapterDTO>(x.Key, x));

Upvotes: 2

Srinivas GV
Srinivas GV

Reputation: 167

Could you try the below code

   var result = chapters.Join(subChapters, c => c.ID, sc => sc.ChapterID, (c, sc) => new { Chapter = c, SubChapter = sc })
                         .OrderBy(x => x.Chapter.Number)
                         .GroupBy(x => x.Chapter.DisplayName)
                         .SelectMany(gr => gr)
                         .ToList<string, SubChapterDTO>(x.Key, x);

Upvotes: 0

Related Questions