I hope this description will suffice, the best way to put it in words is just giving an example of what it is now and how I want it to be. Here goes.
When I execute a certain method, a structure will be generated. Which may have the following content:
> Key: Fa开发者_如何学运维ceBook, Value: Dinges
> Key: SocialMedia, Value: FaceBook
> Key: Medium, Value: SocialMedia
These are associations. According to this Dinges is associated with FaceBook, Facebook is associated with SocialMedia and SocialMedia is associated with Medium.
Now, what I actually need is the following layout:
> Key: FaceBook, Value: Dinges
> Key: SocialMedia, Value: FaceBook
> Key: SocialMedia, Value: Dinges
> Key: Medium, Value: SocialMedia
> Key: Medium, Value: Facebook
> Key: Medium, Value: Dinges
I actually have no idea how to approach this. Any help would be greatly appreciated
So, basically, you want to create the transitive closure of your source dictionary. If you don't have any loops in your dictionary, a simple algorithm creating a new List<Tuple<string, string>>
could look like this:
for each pair (key, value) in your dictionary:
do
list.add(key, value)
if value is not a key in the dictionary, break loop
value = dictionary(value)
loop
EDIT2: Since it's quite easy to translate in C#, here you are:
Dictionary<string, string> dic = new Dictionary<string, string>(); // base data
dic.Add("FaceBook", "Dingens");
dic.Add("SocialMedia", "FaceBook");
dic.Add("Medium", "SocialMedia");
var list = new List<Tuple<string, string>>(); // result
foreach (var de in dic)
{
var value = de.Value;
do
{
list.Add(Tuple.Create(de.Key, value));
} while (dic.TryGetValue(value, out value));
}
foreach (var x in list)
Console.WriteLine(x.Item1 + ": " + x.Item2);
Sounds to me that you want to generate a cartesian product out of the input you have.
Maybe the following article can provide you more input on your problem
http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx
精彩评论