I have a problem with this piece of code, when I do my intersect method everything works fine.
When I do the count on my intersection before the foreach I have 1.
After the foreach, if do the count again after the foreach I have 0, why is this happening? It should always be 1…
var matchedRoles = roles.Intersect(user.Roles);
int before = matchedRoles.Count();
foreach (var matchedRole in matchedRoles)
{
user.Roles.Remove(matchedRole);
}
int after = matchedRoles.Count();
if (matchedRoles.Any())
{
accountRepository.Update(user);
}
It happens because LINQ queries are lazy-evaluated: the result is not produced until it needs to be (which is whenever you call
Count). It stands to reason that if you modifyuser.Rolesin the meantime, theCountcomputed after the modification will be different.If you want to “fix” the result, then you have to force LINQ to make a local copy of the results, e.g. like this:
This way, any further operations on
matchedRoleswill work on a fixed “snapshot” and produce the same results as long as you do not modifymatchedRolesitself.