how to refactor method with two foreach in csharp

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.cs
public void ProcessItems(List<Item> items)
{
    var filteredItems = items.Where(item => item.IsActive);

    var processedItems = filteredItems.Select(item => new ProcessedItem(item.Id, item.Name));

    foreach (var item in processedItems)
    {
        //...
    }
}
270 chars
12 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.cs
public void ProcessItems(List<Item> items)
{
    var filteredItems = FilterItems(items);

    foreach (var item in filteredItems)
    {
        ProcessItem(item);
    }
}

private IEnumerable<Item> FilterItems(List<Item> items)
{
    foreach (var item in items)
    {
        if (item.IsActive)
        {
            yield return item;
        }
    }
}

private void ProcessItem(Item item)
{
    //...
}
405 chars
26 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