C
C#2y ago
malkav

❔ Refactor help`

Can this be written as a Linq expression? I've been trying but I keep failing at it. I'm not as great with Linq...
foreach (Assignment item in _assignments)
{
foreach (AssignedUser user in item.AssigneeId)
{
if (user.UserId != _user.MicrosoftId)
{
_assignmentsNotOnUser.Add(item);
}
}
}
foreach (Assignment item in _assignments)
{
foreach (AssignedUser user in item.AssigneeId)
{
if (user.UserId != _user.MicrosoftId)
{
_assignmentsNotOnUser.Add(item);
}
}
}
3 Replies
WhiteBlackGoose
Hi. Sure, you can SelectMany on _assignments, select on item.AssigneeId, make a where there, that's it Read up on SelectMany a bit
FusedQyou
FusedQyou2y ago
Here you go:
_assignmentsNotOnUser = _assignments
.Where(x => x.AssigneeIds
.Any(y => y.UserId != _user.MicrosoftId))
.ToList();
_assignmentsNotOnUser = _assignments
.Where(x => x.AssigneeIds
.Any(y => y.UserId != _user.MicrosoftId))
.ToList();
Where clause on assignments, gets every assignment where the anyclause equals true. Any returns true for each AssignedUser that matches user.UserId != _user.MicrosoftId. I finish with a ToList() because I stored them in a list in my test. This might not be needed in your case.
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.