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

現在,列表通過帶有聯接的相關子查詢進行選擇,從而消除了父記錄的「重複項」的創建。它應該與原始查詢具有相同的性能。