Friday, June 19, 2009 #

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
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Posted On Friday, June 19, 2009 3:31 PM | Feedback (1)