将LINQ查询语法转换为具有分组的方法语法

时间:2018-04-29 02:33:26

标签: c# linq

我已经做了很多搜索,但是在涉及分组时,我找不到很多可以将LINQ查询语法转换为方法语法的好例子。

例如,这在方法语法中会是什么?

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);

我尝试了这个,但结果却不一样:

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);

如果我将它添加到最后,它将无法编译:

.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>'"

我错过了什么?

2 个答案:

答案 0 :(得分:2)

在GroupBy中使用不同的elementSelector

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));

答案 1 :(得分:0)

您可以尝试下面的代码

   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);