2017-03-07 38 views
1

我有一個List<Scenario>這樣的:LINQ加入,則GROUP BY,置於類的強類型列表

ScenarioNumber  Key  Value 
1     foo  bar 
1     fez  ben 
2     far  baz 
2     fem  bit 

我有一個List<Mapping>這樣的:

Key  MappingValue 
foo  abc 
fez  xyz 
far  123 
fem  bob 

問題:我想通過Key加入這兩個,然後將它們按ScenarioNumber分組爲List<ScenarioNode>

public class ScenarioNode 
{ 
    public int ScenarioNumber { get; set; } 

    public List<ScenarioArgument> Arguments { get; set; } 
} 

ScenarioArgument是與屬性的類:KeyValue,和MappingValue

我有以下的和我被困在Arguments =部分:

var scenarioFormats = from s in this.investment.Scenarios 
         join m in this.keyMappings 
         on new { Key = s.Key, Level = "DEAL" } 
         equals new { Key = m.Key, Level = m.Level } into sm 
         from scen in sm.DefaultIfEmpty() 
         group s by s.ScenarioNumber into sg 
         select new ScenarioNode 
         { 
          ScenarioNumber = sg.Key, 
          Arguments = new List<ScenarioArgument> { } // <<-- now what?     
         }; 
+0

你需要做的是縮短您的查詢,只是'選擇sg'並檢查了每個分組包含調試。一旦你看到返回的數據,你可以制定新的ScenarioNode代碼。我強烈懷疑你的查詢不能按你想要的方式工作。 – tinstaafl

回答

1

你能預料包含ScenarioMappingValue匿名類型:

var scenarioFormats = from s in this.investment.Scenarios 
         join m in this.keyMappings 
         on new { Key = s.Key, Level = "DEAL" } 
         equals new { Key = m.Key, Level = m.Level } into sm 
         from scen in sm.DefaultIfEmpty() 
         group new { Scenario = s, scen?.MappingValue } by s.ScenarioNumber into sg 
         select new ScenarioNode 
         { 
          ScenarioNumber = sg.Key, 
          Arguments = sg.Select(s => new ScenarioArgument 
          { 
           Key = s.Scenario.Key, 
           Value = s.Scenario.Value, 
           MappingValue = s.MappingValue 
          }).ToList() 
         }; 
1

你coult試試這個:

var scenarioFormats = from s in this.investment.Scenarios 
         join m in this.keyMappings on new { Key = s.Key, Level = "DEAL" } equals new { Key = m.Key, Level = m.Level } 
         group new{Scenario=s,KeyMapping=m} by s.ScenarioNumber into sg 
         select new ScenarioNode 
         { 
         ScenarioNumber = sg.Key, 
         Arguments = sg.Select(e=>new ScenarioArgument 
               { 
                Key=e.Scenario.Key, 
                Value=e.Scenario.Key, 
                MappingValue=e.KeyMapping.MappingValue, 
               } 
              )       
         }; 

只是申請首先加入,然後組中的兩個,ScenarioMapping,Scenario.ScenarioNumber,所以,最後您可以使用結果組投影您期望的結果Arguments