webdad3 webdad3 - 1 year ago 126
C# Question

How to switch Key and Values in Dictionary where value might be Null

I have a

with the following values

"abc","Message 1"
"def","Message 1"
"ghi","Message 2"
"jkl","Message 1"
"mno","Message 2"
"pqr","Message 3"

Ultimately I'm trying to group this dictionary by Message.

What I would like to do is loop through this new dictionary and be able to output something like this:

abc, def, jkl : Message 1
ghi, mno : Message 2
prq : Message 3

I'm trying to build another object so I can loop through it, but the
is giving me issues:

var oD = messageDictionary.GroupBy(x => x.Value).ToDictionary(g=>g.Key,g=>g.ToString());

The issue in this example is when the Value part it is
. Because then the
throws a
. How can I solve it?

I've also tried just creating a new dictionary like this:

Dictionary<string, string> newDictionary = new Dictionary<string, string>();
newDictionary = messageDictionary.GroupBy(x => x.Value);

This has an conversion issue.

Maybe there is a better way then using a dictionary? I just thought it would be easier using a dictionary. Any suggestions would be helpful.

Answer Source

I'll stick to the dictionary because you are almost there and this will help you understand what you missed.

The problem is in the Value of the dictionary - You want to select all the item.Key (the original's dictionary's keys) and have that IEnumerable as the value of your new dictionary.

Then you can print it joining the new "values" using string.Join

Dictionary<string, string> values = new Dictionary<string, string>
    { "abc", "Message 1" },
    { "def", "Message 1" },
    { "ghi", "Message 2" },
    { "jkl", "Message 1" },
    { "mno", "Message 2" },
    { "pqr", "Message 3" },
    { "aaa", null }

var result = values.GroupBy(x => x.Value)
                   // In this line the g.Key refers to the `Key` of the IGrouping and not
                   // of the original dictionary. 
                   .ToDictionary(g => g.Key ?? string.Empty, 
                                 // However, on this line each `item` is of the type 
                                 // KeyValuePair and the `.Key` refers to the original's 
                                 // dictionary's key
                                 g => g.Select(item => item.Key).ToList())
                                 //Or: string.Join(", ", g.Select(item => item.Key))

foreach (var pair in result)
    Console.WriteLine("{0}: {1}", string.Join(", ", pair.Value), pair.Key);


enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download