【问题标题】:How to write this nested foreach loop query in LINQ?如何在 LINQ 中编写这个嵌套的 foreach 循环查询?
【发布时间】:2016-10-12 19:53:36
【问题描述】:

您能帮我在 LINQ 中编写这个嵌套的 foreach 循环吗?

c=0
foreach(var e in elements)
{  
     foreach(var a in e.Attributes)
     {
          if(a.Name=="City" && a.GetValue().ToString() == "Oakland")                                                 
                 c += 1;                    
     }
}

【问题讨论】:

  • 向我们展示您的尝试。 c 应该是做什么用的?只是计数?
  • var c = elements.SelectMany(e => e.Attributes).Count(a => a.Name == "City" && a.GetValue().ToString() == "Oakland");

标签: c# .net linq


【解决方案1】:

应该是这样的(使用SelectManyCount 方法):

int c = elements.SelectMany(e => e.Attributes)
                .Count(a => a.Name == "City" && a.GetValue().ToString() == "Oakland");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 2020-12-02
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多