I have two or more arrays — one with IDs, one or more with string values. I want to merge these into a hash table so I can look up values by ID.
The following function does the job, but a shorter and sweeter version (LINQ?) would be nice:
Dictionary<int, string[]> MergeArrays( IEnumerable<int> idCollection, params IEnumerable<string>[] valueCollections ) { var dict = new Dictionary<int, string[]>(); var idL = idCollection.Count(); while ( idL-- > 0 ) { dict[idCollection.ElementAt( idL )] = new string[valueCollections.Length]; var vL = valueCollections.Length; while ( vL-- > 0 ) dict[idCollection.ElementAt( idL )][vL] = valueCollections[vL].ElementAt( idL ); } return dict; }
Any ideas?
That’s very inefficent at the moment – all those calls to ElementAt could be going through the whole sequence (as far as they need to) each time. (It depends on the implementation of the sequence.)
However, I’m not at all sure I even understand what this code is doing (using foreach loops would almost certainly make it clearer, as would iterating forwards instead of backwards. Could you give some sample input? and expected outputs?
EDIT: Okay, I think I see what’s going on here; you’re effectively pivoting valueCollections. I suspect you’ll want something like:
It’s pretty ugly though. If you can make idCollection an array to start with, it would frankly be easier.
EDIT: Okay, assuming we can use arrays instead:
I’ve corrected (hopefully) a bug in the first version – I was getting confused between which bit of the values was an array and which wasn’t. The second version isn’t as declarative, but I think it’s clearer, personally.