Reputation: 73
I'm learning some LINQ. When having something like this:
foreach (var user in result.Items)
{
if (!(user.UserId.Equals(session.UserId)))
{
user.CanBeDeleted = true;
}
}
How it can be resolved with LINQ? Is it better performing LINQ or the foreach-if combination?
Upvotes: 1
Views: 735
Reputation: 3188
result.Items.Where(user =>
!user.UserId.Equals(session.UserId)).ToList()
.ForEach(user => user.CanBeDeleted = true);
Upvotes: 0
Reputation: 460018
In most cases LINQ does not make your program run faster but it makes your code more readable and therefore easier to maintain.
But if you need to modify something LINQ is not the right tool. The Q
stands for query. Use a plain loop to modify it. But you can filter what you have to modify:
var toBeDeleted = result.Items.Where(u => u.UserId != session.UserId);
Now you can use a loop to execute it and change the User
:
foreach(User user in toBeDeleted)
user.CanBeDeleted = true;
Upvotes: 4