[英]LINQ join, then group by, into strongly-typed List of classes
我有一個這樣的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?
};
您可以嘗試以下方法:
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.ScenarioNumber
Scenario
和Mapping
分組,因此,最后,您可以使用結果組在Arguments
屬性中投影期望的結果
您可以投影一個包含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()
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.