2017-03-03 64 views
0

我在LINQ以下选择查询:与Linq的分组到列表

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

目前这几个指数(INT)值一起选择一个证据的对象,因此,例如我可能会得到5条记录回来,所有的相同的证据对象和5个不同的指数。

我想要做的只是返回带有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财产。我已经尝试了几个我在网上找到的建议,但是没有一个能够帮上忙。我认为这是我的一个小错误,但我现在要盲目地执行代码了!

更新:

确切错误:

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

+4

那么确切的错误是什么? [mcve]会让你更容易帮助你。 –

+1

'SelectMany'是为了列出一个列表。连接表不会将列表嵌套到列表中。如果将其更改为“选择”会怎样?顺便说一句,'r'似乎是分组的一部分。 –

+0

@JonSkeet我已经用确切的错误更新了这个问题。 – XN16

回答

1

由于@JeroenvanLangen在我的问题的评论所说,我并不需要SelectMany只有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 
    group new { e, r } by new { e } 
    into g 
    select new 
    { 
     Evidence = g.Key, 
     RequirementIndices = g.Select(x => x.r.Index).ToList() 
    }; 
0

您应该能够通过避免在顶层加入来产生相同的分组结果:

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

现在,列表通过带有联接的相关子查询进行选择,从而消除了父记录的“重复项”的创建。它应该与原始查询具有相同的性能。