c# - 如何在值可能为空的字典中切换键和值

标签 c# linq dictionary

我有一个 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);

这有一个转换问题。

也许有比使用字典更好的方法?我只是认为使用字典会更容易。任何建议都会有所帮助。

最佳答案

我会坚持查字典,因为你几乎已经到了,这将帮助你了解你错过了什么。

问题出在 dictionaryValue - 您想要选择所有 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);
}

输出:

enter image description here

关于c# - 如何在值可能为空的字典中切换键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38775634/

相关文章:

c# - 从 Visual Studio 启动 ASP.NET Core 不是从构建文件夹启动

c# - string.split 但保持顺序匹配

c# - Linq:选择 1:N 关系的 N 侧的项目

python - 从冗长的字典生成时,Pandas DataFrame.from_dict() 性能不佳

python - 通过在 python 中对字典进行排序来提取键列表

java - 将 HashMap 添加到 TreeSet 的奇怪行为

c# - 绑定(bind)到 VM 上同一集合的多个 ItemsControl 无法正确呈现

c# - 带有 MySQL 的 ASP.NET MVC EF 需要 .dll 及其用法?

sql-server - EF Core Linq 中子查询的总和

.net - Linq 将复杂类型聚合成一个字符串