EDIT: This question may be marked as a duplicate of this question.
Are there any differences (performance or otherwise) between using the 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); }
Instead, I can use this code to accomplish the same task:
typeof(Person) .GetProperties() .ToList() .ForEach(property => Validate(property.Name));
When is a loop structure better than a chain of methods?
Here is another example where I used the ForEach method, but could just easily use 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); }
c # foreach linq
Jake
source share