Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialReza R. Makwandi
6,357 PointsBest practice for a search with foreach loop
Hi, i have the following method:
public void SearchForEntry(string name)
{
bool _resultFound = false;
foreach (Entry entry in _entry)
{
if (entry.HasFirstName(name))
{
Console.WriteLine("Found: " + entry.FirstName + " " + entry.LastName + ".");
_resultFound = true;
}
}
if (!_resultFound)
{
Console.WriteLine("No result found");
}
}
I feel like the bool var is a code smell, is the a best practice for this type of search? A way to search with an foreach and output found result (many times) / no result found (just once)?
1 Answer
Steven Parker
231,269 PointsThis is a common construct. The repeating assignments are faster than any kind of conditional you might use to cause the assignment to be performed only once.