2017-03-03 3 views
0

私は、LINQで、次の選択クエリがあります。例えば、私は戻って5つのレコードを取得する可能性がありますのでは、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型)の値と一緒に証拠オブジェクトを選択し、すべてとは同じEvidenceオブジェクトと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) 
}; 

エラーがRequirementIndicesプロパティに割り当てられているSelectManyの周りに発生します。これは、1つのような試みです。私はオンラインで見つけたいくつかの示唆を試しましたが、どれも助けてくれませんでした。私はそれが私の部分で小さなエラーだと思うが、私は今、コードブラインドに行くよ!

更新:

正確なエラー:

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'はリストのリストを平坦化することです。テーブルを結合してもリストはリストに入れられません。もしそれを 'Select'に変更すればどうなりますか?ところで、「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() 
    }; 

今リストは、親レコードの「重複」の作成を排除参加と相関サブクエリ、を介して選択されます。元のクエリと同じパフォーマンスが必要です。

関連する問題