About Me

Training

Develop With Passion® - Developer Bootcamp

Subscribe

Combining two disparate collections

Written July 27, 2009 at 13:40 MDT Tagged c sharp and programming

During class last week someone had written a piece of code right near the end of the last evening and I committed to showing them a potential refactoring that could be used. Here is the piece of code in question:

var info_list = new List<ResolverConfigurationInfo>(parser());

var resolver_items = info_list.Select(x => factory(x)).ToList();

var index = 0;

parser().each(item =>

{

resolvers.Add(item.AbstractType, resolver_items[index]);

index++;

});


The code is not really complicated. The messiness comes from the fact that an index needs to be maintained so that it can be used to lookup into another equally sized collection that is not the target of the iteration. There are obviously lots of ways to solve this, but I thought "why not just flatten the two collections into a single collection which eliminates the need for the index. Here is the resulting code that was produced:

var info_list = new List<ResolverConfigurationInfo>(parser());

var resolver_items = info_list.Select(x => factory(x)).ToList();

info_list.union(resolver_items).each(item => resolvers.Add(item.first_value.AbstractType, item.second_value));


The union method is a new extension method that will take 2 disparate collections of the same size and combine them into a singular collection of Tuple<T,U> types. I created a simple Tuple class as nothing more than as an immutable parameter object. Here is the resulting code for it (very simple):

public class Tuple<FirstType, SecondType>

{

public FirstType first_value { get; private set; }

public SecondType second_value { get; private set; }

public Tuple(FirstType first, SecondType second_type)

{

this.first_value = first;

this.second_value = second_type;

}

}


Finally the code that pulls it all together is here in the extension method that does the heavy lifting:

static public IEnumerable<Tuple<FirstType, SecondType>> union<FirstType, SecondType>(this IEnumerable first_set,

IEnumerable second_set)

{

Check.not_null(first_set,second_set);

var first_list = first_set.ToList();

var second_list = second_set.ToList();

Check.ensure(first_list.Count == second_list.Count);

for (var index = 0; index < first_list.Count; index++) yield return new Tuple<FirstType, SecondType>(first_list[index], second_list[index]);

}


This method hides the details of the indexer into a utility method that can be used anywhere where 2 sets of disparate items of the same length need to be combined into a singular set.
Thoughts?
Develop With Passion!!