user1287678
user1287678

Reputation: 73

Refactor nested 'foreach' and 'If' to LINQ

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

Answers (2)

Kilazur
Kilazur

Reputation: 3188

result.Items.Where(user => 
    !user.UserId.Equals(session.UserId)).ToList()
    .ForEach(user => user.CanBeDeleted = true);

Upvotes: 0

Tim Schmelter
Tim Schmelter

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

Related Questions