Linq分组到列表中

Linq grouping into list

我在 linq 中有以下 select 查询:

var something = 
    from te in taskEvidences
    join e in evidences on te.EvidenceId equals e.Id
    join tr in taskRequirements on te.TaskListId equals tr.TaskListId
    join r in newSelectableModule.Requirements on tr.RequirementListId equals r.Requirement.Id
    select new
    {
        Evidence = e,
        RequirementIndices = r.Index
    };

目前它select是一个证据对象以及几个索引 (int) 值,因此例如我可能会返回 5 条记录,所有记录都具有相同的证据对象和 5 个不同的索引。

我想做的只是 return 带有 Evidence 对象的单个记录和 List<int> 索引。我尝试使用分组,但我不断收到有关无法从用法中推断出类型的错误。这是一个这样的尝试:

group new {e, r} by new {e}
into g
select new
{
    Evidence = g.Key,
    RequirementIndices = g.SelectMany(x => x.r.Index)
};

错误发生在将 SelectMany 分配给 RequirementIndices 属性 前后。我已经尝试了几个我在网上找到的建议,但其中 none 有帮助。我认为这是我的一个小错误,但我现在要代码盲了!

更新:

确切错误:

The type arguments for method 'Enumerable.SelectMany(IEnumerable, Func>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

正如@JeroenvanLangen 在对我的问题的评论中所建议的,我不需要 SelectManySelect:

var something = 
    from te in taskEvidences
    join e in evidences on te.EvidenceId equals e.Id
    join tr in taskRequirements on te.TaskListId equals tr.TaskListId
    join r in newSelectableModule.Requirements on tr.RequirementListId equals r.Requirement.Id
    group new { e, r } by new { e }
    into g
    select new
    {
        Evidence = g.Key,
        RequirementIndices = g.Select(x => x.r.Index).ToList()
    };

您应该能够通过避免在顶层进行联接来生成相同的分组结果:

var something = 
    from te in taskEvidences
    join e in evidences on te.EvidenceId equals e.Id
    select new
    {
        Evidence = e,
        RequirementIndices = (
            from tr in taskRequirements
            join r in newSelectableModule.Requirements on tr.RequirementListId equals r.Requirement.Id
            where te.TaskListId equals tr.TaskListId
            select r.Index
        ).ToList()
    };

现在通过关联子查询和连接选择列表,这消除了父记录的创建 "duplicates"。它应该具有与原始查询相同的性能。