This is probably a simple question, but the answer is eluding me.
I have a collection of strings that I’m trying to convert to a dictionary.
Each string in the collection is a comma-separated list of values that I obtained from a regex match. I would like the key for each entry in the dictionary to be the fourth element in the comma-separated list, and the corresponding value to be the second element in the comma-separated list.
When I attempt a direct call to ToDictionary, I end up in some kind of loop that appears to kick me of the BackgroundWorker thread I’m in:
var MoveFromItems = matches.Cast<Match>()
.SelectMany(m => m.Groups["args"].Captures
.Cast<Capture>().Select(c => c.Value));
var dictionary1 = MoveFromItems.ToDictionary(s => s.Split(',')[3],
s => s.Split(',')[1]);
When I create the dictionary manually, everything works fine:
var MoveFroms = new Dictionary<string, string>();
foreach(string sItem in MoveFromItems)
{
string sKey = sItem.Split(',')[3];
string sVal = sItem.Split(',')[1];
if(!MoveFroms.ContainsKey(sKey))
MoveFroms[sKey.ToUpper()] = sVal;
}
I appreciate any help you might be able to provide.
The problem is most likely that the keys have duplicates. You have three options.
Keep First Entry (This is what you’re currently doing in the
foreachloop)Keys only have one entry, the first one that shows up – meaning you can have a
Dictionary:Keep All Entries, Grouped
Keys will have more than one entry (each key returns an
Enumerable), and you use aLookupinstead of aDictionary:Keep All Entries, Flattened
No such thing as a key, simply a flattened list of entries:
You could also use a tuple here (
Tuple.Create(x[3], x[1]);) instead.Note: You will need to decide where/if you want the keys to be upper or lower case in these cases. I haven’t done anything related to that yet. If you want to store the key as upper, just change
x[3]tox[3].ToUpper()in everything above.