Replacing Nested foreach Loops with LINQ

One of the things that drives me nuts is heavily nested code. Especially if it’s heavily nested and doesn’t even need to accomplish much. So, recently I encountered a section of code at work that is simply 3 nested foreach loops that is performing one action on every permutation of the values being iterated. It looks ugly, and there’s got to be a better way. It’s already O(n) = n^3, there’s gotta be something I can do to at least make it look pretty.

I’m admittedly fairly new to LINQ and lambda expressions. I’m learning quickly though and I have a strong desire to get better faster. After some googling, I didn’t find exactly what I needed but I was able to cobble something together.

I started with this:

foreach (var group in groups)
    foreach (var move in moves)
        foreach (var time in times)
            values[group.Id, move.Id, time.Id] = value;

Just looking at it there makes me cringe. So much wasted space. I replaced it with this:

var query = from group in groups
            from move in moves
            from time in times
            select new { GroupId = group.Id, MoveId = move.Id, TimeId = time.Id };

foreach (var item in query)
    values[item.GroupId, item.MoveId, item.TimeId] = value;

Yes, it’s more line, but they are denser. There’s less wasted space. The query creates an IEnumerable of an anonymous type, which I then iterate though to assign the values.

I still need to run it through a profiler, but I believe it runs faster too.

There’s probably a better way to do this using a lambda expression that is even faster and performs the task right in the LINQ expression, but I’m not sure on how to accomplish that yet. I’m getting there though, and that makes me happy.

Happy new year!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s