Bookmark and Share

Refactor ForEach to AddRange

by KodefuGuru 19. June 2009 16:31

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.

blog comments powered by Disqus

KodefuGuru.GetInfo()

Chris Eargle
LinkedIn Twitter Technorati Facebook

Chris Eargle
C# MVP, INETA Community Champion


MVP - Visual C#

 

INETA Community Champions
Friend of RedGate
Telerik .NET Ninja
Community blogs & blog posts

I am a #52er

I have joined Anti-IF Campaign


World Map

Tag cloud

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010