c# - foreach 循环与 ForEach 方法 - 区别?

标签 c# linq foreach

<分区>

使用 foreach 循环或 ForEach LINQ 方法之间是否存在任何差异(性能或其他方面)?

对于上下文,这是我方法之一的一部分:

foreach (var property in typeof(Person).GetProperties())
{
    Validate(property.Name);
}

我也可以使用这段代码来执行相同的任务:

typeof(Person)
    .GetProperties()
    .ToList()
    .ForEach(property => Validate(property.Name));

什么时候使用循环结构比使用方法链更好?

这是另一个示例,我使用了 ForEach 方法,但可以轻松地使用 foreach 循环和变量:

// LINQ
PrivateData.Database.Users
           .Cast<User>()
           .Where(user => user.LoginType == LoginType.WindowsUser)
           .Select(user => new { Name = user.Name, Login = user.Login })
           .ToList()
           .ForEach(result => WriteObject(result));

// Loop
var users = PrivateData.Database.Users
               .Cast<User>()
               .Where(user => user.LoginType == LoginType.WindowsUser)
               .Select(user => new { Name = user.Name, Login = user.Login });

foreach(var user in users)
{
    WriteObject(user);
}

最佳答案

我会推迟你到Eric Lipperts blog "foreach" vs "ForEach" .作为 C# 编译器团队的前任首席开发人员,我认为他的观点是正确的。

摘录:(引用.ForEach())

The first reason is that doing so violates the functional programming principles that all the other sequence operators are based upon. Clearly the sole purpose of a call to this method is to cause side effects. The purpose of an expression is to compute a value, not to cause a side effect. The purpose of a statement is to cause a side effect. The call site of this thing would look an awful lot like an expression (though, admittedly, since the method is void-returning, the expression could only be used in a “statement expression” context.) It does not sit well with me to make the one and only sequence operator that is only useful for its side effects.

关于c# - foreach 循环与 ForEach 方法 - 区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33480820/

相关文章:

c# - 使用 Linq 更新嵌套属性

c# - 24位整数

c# - 在Linq中将Dictionary <int,Dictionary <int,Foo>>转换为IEnumerable <IEnumerable <Foo>>的最简单方法?

c# - 更新对从 linq 查询返回的对象的原始引用

javascript - forEach 循环不更新对象值

c# - 如何在用户单击浏览器停止按钮时停止服务器端处理 (ASP.net C#)

c# - 使用原始 SQL 预加载实体

c# - 使用 LINQ 从使用 C# 的 HTML 中提取所有隐藏的输入

c# - foreach 中的 List<T> 与 IEnumerable<T>

php - 使用 PHP 在 x 个 DIV 之后插入不同的 DIV