Edit: I tested your version of Invert
and that seems to work just fine. Are you getting confused by the default ToString()
output? If you directly try to print Program.Invert(dictionary)[find]
, you will not get the output you expect since the default ToString()
is not very helpful (due to the fact that the object you are trying to print does not override object.ToString()
). You will have to iterate through your list of values and individually print each one. Assuming TKey
overrides ToString()
, you will get the output you want. For example,
Console.WriteLine("{0} found in: ", find);
foreach (var val in Program.Invert(dictionary)[find])
{
Console.WriteLine(val);
}
Previous Answer (saved for posterity):
Alright, you mentioned that something is wrong in your Invert
method. I tried to write up an Invert
method of my own and here's what I came up with. I've broken up the method calls in to separate parts so that it's clear what I'm doing.
static Dictionary<TItem, IEnumerable<TKey>> Invert<TKey, TItem>(Dictionary<TKey, IEnumerable<TItem>> dictionary)
{
// Get collection of all the values which will be keys in the new inverted dictionary
var invertedDictKeys = dictionary.SelectMany(keyValPair => keyValPair.Value).Distinct();
// Perform the invert
var invertedDict =
invertedDictKeys.Select(
invertedKey =>
new KeyValuePair<TItem, IEnumerable<TKey>>(invertedKey, dictionary.Keys.Where(key => dict[key].Contains(invertedKey))));
// Convert to dictionary and return
return invertedDict.ToDictionary(keyValPair => keyValPair.Key, keyValPair => keyValPair.Value);
}