patterncsharpModerate
Refactor foreach statement to LINQ
Viewed 0 times
foreachlinqrefactorstatement
Problem
I have been working on a project and I'm actually refactoring some code. I have encountered myself with lots of foreach and if statements, which could be easily replace with LINQ.
But I have this code snippet, that I wonder how I could make it more functional style.
The
But I have this code snippet, that I wonder how I could make it more functional style.
foreach (var notification in notifications)
{
if (_emailService.SendEmail(notification.Message.Subject, notification.Message.Body, notification.Message.MailTo))
{
successNotificationIDs.AddRange(notification.ID);
}
else
{
errorCount++;
}
}The
SendEmail method of the EmailService returns a bool. If its execution has been successfully, it will add an IEnumerable of Int to a declared collection (successNotificationsIDs). If not, I will increase the errorCount variable.Solution
LINQ isn't a silver bullet. It stands for Language-INtegrated-Query, which allows querying objects.
Querying objects isn't something that's supposed to have side-effects. However this is precisely what you loop's body is doing.
Therefore, refactoring it to use LINQ, if at all possible, would make it much less readable than the
You could always create a
Now the loop body you have, is using
Querying objects isn't something that's supposed to have side-effects. However this is precisely what you loop's body is doing.
Therefore, refactoring it to use LINQ, if at all possible, would make it much less readable than the
foreach loop you have here.You could always create a
Task object for each notification, and then run that.Now the loop body you have, is using
AddRange to add what appears to be a single value. Unless notification.ID is an IEnumerable, you should be using the Add method to add a single value to your successNotificationIDs.Context
StackExchange Code Review Q#42977, answer score: 12
Revisions (0)
No revisions yet.