Is there any differences (performance or otherwise) between using a foreach loop or the ForEach
LINQ
method?
For context, this is part of one of my methods:
foreach (var property in typeof(Person).GetProperties())
{
Validate(property.Name);
}
I can alternatively use this code to perform the same task:
typeof(Person)
.GetProperties()
.ToList()
.ForEach(property => Validate(property.Name));
When would be using the loop structure be better than using method chaining?
Here's another example where I've used the ForEach
method, but could just have easily used a foreach loop and a variable:
// 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);
}