嵌套到Linq的foreach

时间:2017-08-14 07:10:16

标签: c# linq

我是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 
     }));

3 个答案:

答案 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 
      }));
  • Where - 根据谓词过滤一系列值
  • Select - 将序列的每个元素投影到新表单中

答案 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 }));