如何从字典中的不同键中获取相同的值?

问题描述

新手警报: 我刚开始使用Dictionary或与keyvaluePair相关的任何事物。
我有一个Dictionary,并向其中添加了一些值。

var first_choice_dict = new Dictionary<string,int>();
名称是键,数字是表示其选择的值。

Bob,2
Chad,1
Dan,3
Eden,5
Fred,1
Greg,4
Hope,2
Ivan,1
Jim,2

请问是否有一种方法可以按相同的值对它们进行排序,然后仅将键移到新字典中(或者也可以将值移到新字典中),如下所示:

已排序

Abe,1
Chad,1
Fred,1
Ivan,1
......

新选择词典1
Abe,Chad,Fred,Ivan

解决方法

您根本不想对它们进行“排序”。您想按值分组,然后构建一个新字典,其中选择是关键,因为我建议使用<!DOCTYPE html> <html> <body> <video id="myVideo" width="550" height="400" controls style=" z-index: 2; top: 50px; left: 100px; position: absolute; );"> <source src="some_video.mp4" type="video/mp4"> </video> <div id="myPic" class="images" width="550" height="400" style=" z-index: 1; top: 80px; left: 140px; position: absolute; );"> <img src="some_pic.jpg" /> </div> <script type='text/javascript'> document.getElementById('myVideo').addEventListener('ended',myHandler,false); const img = document.getElementById('myPic'); const video = document.getElementById('myVideo'); function myHandler(e) { // now the video has to hide,and show the img: //video.style.display = "none: //img.style.display = "block" //# swap their layer positioning img.style.zIndex = "2"; //# makes top video.style.zIndex = "1"; //# makes bottom } </script> </body> </html>

IEnumerable<string>

如果您想将字符串作为值,并用逗号分隔名称:

Dictionary<int,IEnumerable<string>> choiceDict = userChoicesDict
    .GroupBy(kv => kv.Value)
    .ToDictionary(g => g.Key,g => g.Select(kv => kv.Key));