我有List<Scenario>
这样:
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
是一个包含属性的类:Key
,Value
和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 :(得分:1)
你可以试试这个:
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,
}
)
};
首先应用加入,然后按Scenario
对Mapping
和Scenario.ScenarioNumber
进行分组,这样,最后您可以预测{{1}中您期望的结果使用结果组
答案 1 :(得分:1)
您可以投射包含Scenario
和MappingValue
的匿名类型:
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()
};