我是LINQ的新手,帮我将这个嵌套的代码行转换为LINQ。
foreach(var rule in rules)
{
foreach(var package in packages)
{
if(rule.KeyFrom == package.Key || rule.KeyTo == package.Key)
{
filteredRule.Add(new RuleModel{Package = new List<string>{rule.KeyTo, rule.KeyFrom}, Rule = rule.Rule});
}
}
}
尝试查询:
rules.SelectMany(r => packages.Select(p => p.Key == r.KeyFrom || p.Key == r.KeyTo))
.Select(new RuleModel {
Package = new List<string>{ r.Keyfrom, r.KeyTo},
Rule = r.Rule
}));
答案 0 :(得分:3)
你快到了。您的问题是SelectMany
使用Select
过滤使用Where
的{{1}}:
rules.SelectMany(r => packages.Where(p => p.Key == r.KeyFrom || p.Key == r.KeyTo))
.Select(r => new RuleModel {
Package = new List<string>{ r.Keyfrom, r.KeyTo},
Rule = r.Rule
}));
答案 1 :(得分:2)
您必须使用SelectMany
。
代码将是这样的:
var ruleModels = rules.SelectMany(r => r.packages).Where(rule.KeyFrom == package.Key || rule.KeyTo == package.Key).Select(r => new RuleModel{Package = new List<string>{r.KeyTo, r.KeyFrom}, Rule = r.Rule});
filteredRule.AddRange(ruleModels);
答案 2 :(得分:0)
您可以尝试以下代码:
filteredRule.AddRange(rules.Where(b =>
packages.Any(a => b.KeyFrom == a.Key || b.KeyTo == a.Key)).select(
p=>new new RuleModel { Package = new List<string>
{ p.KeyTo, p.KeyFrom }, Rule = p.Rule }));