Reputation: 1408
I have a function that accepts a list of objects (in my case, comments on a blog post) and a user. Then the function should iterate over each comment in the list and set the IsCommenter
boolean property to true or false depending on if the comments author id is equal to that of the user which was passed in. The concept being the picture below:
If I'm logged in as Taylor Swift, and the below list is sent to this function as well as Taylor Swift the user, then this boolean function should return false (because the first comment was made by Happy Gilmore), true, true, true.
But it is not working. It is doing the first comment, setting it to true or false, then exiting out of the foreach loop setting everything that follows the first object in the list of comments to false.
public bool IsCommenter(List<Comment> comments, ApplicationUser user)
{
if (user == null) throw new ArgumentNullException("User can't be null");
if (comments.Count() <= 0) throw new ArgumentException("Must have more than one comment.");
foreach(var comment in comments)
{
if (comment.AuthorId == user.Id)
{
return comment.IsCommenter = true;
} else
{
return comment.IsCommenter = false;
}
}
return false;
}
I suspect it may be because of the final return false
in the function, however, I put that in there because without it, I get an error that not all code paths return a value (which I don't see how that could be the case when it's an if/else, not an if/elseif. Any thoughts on making this work?
Upvotes: 0
Views: 966
Reputation: 51009
Because you have return
in the loop. Remove it
foreach(var comment in comments)
{
if (comment.AuthorId == user.Id)
{
comment.IsCommenter = true;
}
else
{
comment.IsCommenter = false;
}
}
Or simplified
foreach(var comment in comments)
{
comment.IsCommenter = comment.AuthorId == user.Id;
}
Upvotes: 3