To refactor a method with two foreach statements in C#, you can consider using LINQ or create a separate method that performs the iteration. Here's an example of refactoring using LINQ:
main.cs270 chars12 lines
In the example, we used the Where()
method to filter the items based on the IsActive
property, then used the Select()
method to project the filtered items into a new type. Afterward, we used a single foreach
loop to iterate over the processed items.
Another option is to extract the iteration logic to a separate method, like this:
main.cs405 chars26 lines
In this example, we created a new method FilterItems()
that returns an IEnumerable
of filtered items using yield return
. Then, we used a single foreach
loop to iterate over the filtered items and called the ProcessItem()
method for each item.
These refactorings aim to make the code easier to read, more maintainable, and less prone to errors in the future.
gistlibby LogSnag