我有一个 dictionary<string,string>
具有以下值
"abc","Message 1"
"def","Message 1"
"ghi","Message 2"
"jkl","Message 1"
"mno","Message 2"
"pqr","Message 3"
最终,我尝试按消息对这本词典进行分组。
我想做的是遍历这个新字典并能够输出如下内容:
abc, def, jkl : Message 1
ghi, mno : Message 2
prq : Message 3
我正在尝试构建另一个对象以便循环遍历它,但是 ToDictionary()
给我问题:
var oD = messageDictionary.GroupBy(x => x.Value).ToDictionary(g=>g.Key,g=>g.ToString());
问题 在这个例子中,值部分是 NULL
.因为那时 ToDictionary
抛出 NullReferenceException
.我该如何解决?
我也试过像这样创建一个新字典:
Dictionary<string, string> newDictionary = new Dictionary<string, string>();
newDictionary = messageDictionary.GroupBy(x => x.Value);
这有一个转换问题。
也许有比使用字典更好的方法?我只是认为使用字典会更容易。任何建议都会有所帮助。
最佳答案
我会坚持查字典,因为你几乎已经到了,这将帮助你了解你错过了什么。
问题出在 dictionary
的 Value
- 您想要选择所有 item.Key
(原始字典的键)和将 IEnumerable
作为新字典的值。
然后您可以使用 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))
.ToList();
foreach (var pair in result)
{
Console.WriteLine("{0}: {1}", string.Join(", ", pair.Value), pair.Key);
}
输出:
关于c# - 如何在值可能为空的字典中切换键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38775634/