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.

Tags: , , , , ,

Kodefu

Comments

6/19/2009 4:32:15 PM #

trackback

Trackback from DotNetKicks.com

Refactor ForEach to AddRange

DotNetKicks.com

6/19/2009 4:35:17 PM #

trackback

Trackback from DotNetShoutout

Refactor ForEach to AddRange

DotNetShoutout

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.6.0.0
Theme by Mads Kristensen

Whois KodefuGuru

Chris Eargle

Chris Eargle
.NET Community Champion

LinkedIn Twitter Technorati Facebook

MVP - Visual C#

 

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

I am a #52er


World Map

RecentComments

Comment RSS

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