简体   繁体   English

如何在C#中添加where到foreach循环中

[英]How can I add a where into my foreach loop in C#

I have the following: 我有以下内容:

foreach ( var menuItem in  Model.menuItems) {
  if (menuItem.Type == "02") {

  }
}

The code within the foreach executes only when Type==2 so is there some way that I could add the check for Type == "02" into the top part of my loop. foreach中的代码仅在Type == 2时执行,因此我可以通过某种方式将Type ==“02”的检查添加到循环的顶部。

List(Of T).ForEach Method : Performs the specified action on each element of the List(Of T) . List(Of T).ForEach MethodList(Of T)每个元素执行指定的操作。

Model.menuItems.Where(c => c.Type == "02").ToList().ForEach(delegate(type data)
        {
            //code to execute

        });

Try 尝试

foreach ( var menuItem in  Model.menuItems.Where(mi => mi.Type == "02") {

}

LINQ: LINQ:

foreach (var menuItem in  Model.menuItems.Where(item => item.Type == "02")) {
}

You can do this with linq using the following: 您可以使用以下命令使用linq执行此操作:

foreach ( var menuItem in  Model.menuItems.Where(m=>m.Type == "02") {

}

If your menuItems already are enumerable: 如果你的menuItems已经是可枚举的:

foreach (var menuItem in  Model.menuItems.Where(c => c.Type == "02")) { 
} 

Otherwise try: 否则尝试:

foreach (var menuItem in  Model.menuItems.AsEnumerable().Where(c => c.Type == "02")) { 
} 

Or: 要么:

foreach (var menuItem in  Model.menuItems.ToList().Where(c => c.Type == "02")) { 
} 

foreach ( var menuItem in  Model.menuItems.Where(m => m.Type == "02")) {}

how about 怎么样

foreach ( var menuItem in  Model.menuItems.Where(m => m.Type == "02")) {

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM