Refactor ForEach to AddRange

Here’s a refactoring I used to do some minor cleanup today. The programmer was iterating through a dictionary to add values to a list. No logic was contained within the iterator.

public void AddCodes(Dictionary<int, string> indexedCodes)
{
    foreach (var code in indexedCodes.Values)
    {
        Codes.Add(code);
    }
}

This can be simplified by using the list’s AddRange method.

public void AddCodes(Dictionary<int, string> indexedCodes)
{
    Codes.AddRange(indexedCodes.Values);
}

If you’re reassigning, this is even more unnecessary; just use the ToList method provided by LINQ.

public void AssignCodes(Dictionary<int, string> indexedCodes)
{
    Codes = indexedCodes.Values.ToList();
}

This isn’t much of a change, but it did simplify things. The real world example was surrounded by other blocks of code that made it difficult to read. This one, small change helped improve the readability of the method.

Note: Cross posted from KodefuGuru.
Permalink

Print | posted on Friday, June 19, 2009 3:31 PM

Comments on this post

# re: Refactor ForEach to AddRange

Requesting Gravatar...
I've been using AddRange quite a bit myself. Another way to reduce code for a foreach is when working on a IList<T> there is the ForEach extension method.
people.ForEach(x=>x.FirstName.ToUpper());

I've been using this in conjunction with a search and replace routine that uses a set of testable delegates that are just chained onto the list in question.
Left by Jeff Klawiter on Jun 23, 2009 10:13 AM

Your comment:

 (will show your gravatar)