C# LINQ ForEach 可以有 if 语句吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17461367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:31:34  来源:igfitidea点击:

Can LINQ ForEach have if statement?

c#linqlistif-statementforeach

提问by abc cba

Is it possible to add if-statement inside LINQ ForEachcall?

是否可以if在 LINQForEach调用中添加-statement ?

sequence.Where(x => x.Name.ToString().Equals("Apple"))
        .ToList()
        .ForEach( /* If statement here */ );

采纳答案by Keith Nicholas

you can do the following...

您可以执行以下操作...

List.Where(x => x.Name.ToString().Equals("Apple").ToList()
    .ForEach( x => { if(x.Name == ""){}} );

回答by TGH

Yes, It takes a lambda expressions, so you can put any valid c# expression in there

是的,它需要一个 lambda 表达式,因此您可以在其中放置任何有效的 c# 表达式

回答by tariq

Yes, if-statement is commonly used inside the ForEach as below:

是的,在 ForEach 中通常使用 if 语句,如下所示:

sequence.Where(x => x.Name.ToString().Equals("Apple"))
    .ToList()
    .ForEach( x =>
     {
       if(someCondition)
       {
         // Do some stuff here.
       }  
     });

回答by euan jones

Old thread but throwing an in my opinion cleaner syntax

旧线程,但在我看来抛出了更干净的语法

foreach(var item in sequence.Where(s => s.Name.ToString() == "Apple"))
{
 // do whatever
}