C#

Reza R. Makwandi
Reza R. Makwandi
4,822 Points

Best 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
Steven Parker
163,764 Points

This 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.