简体   繁体   English

在字典中查找对

[英]c# Finding pairs in dictionary

For my project i made a dictionary that has a random double and a string that belongs to that double: Dictionary<double, string> myDict = new Dictionary<double, string>(); 对于我的项目,我制作了一个字典,该字典具有一个随机的double和一个属于该double的字符串: Dictionary<double, string> myDict = new Dictionary<double, string>();

For this project i know that the double is a random value, and within the dictionaries all strings are unique, with the exception that about 80% one of them is twice in the dictionary. 对于这个项目,我知道double是一个随机值,并且在字典中所有字符串都是唯一的,除了其中大约80%的字符串在字典中是两次。 So what i want to do, is find the 2 strings that are a pair (the same string) and find the 2 double values that belong to these 2 string. 因此,我想做的是找到两个成对的字符串(相同的字符串),并找到属于这两个字符串的2个double值。

Basically my idea of doing this is by using IEnumerator counter = myDict.GetEnumerator(); 基本上,我这样做的想法是使用IEnumerator counter = myDict.GetEnumerator(); and use the while (counter.MoveNext() == true) to start another IEnumerator that loops again through all the entries of the dictionary and compares by string, so if will find the pairs this way. 并使用while (counter.MoveNext() == true)启动另一个IEnumerator,该IEnumerator再次循环遍历字典的所有条目并按字符串进行比较,因此,如果将以这种方式找到这些对。 So for each entry in the dictionary, it will loop through the whole dictionary again to find pairs. 因此,对于字典中的每个条目,它将再次遍历整个字典以查找对。

Now i get the feeling this might not be the best solution to handle this. 现在,我感觉这可能不是解决此问题的最佳解决方案。 Are there alternatives to find the pairs in the dictionary, or is this looping through the only real way of doing this? 是否有其他方法可以在字典中找到对,或者这是唯一循环的方式?

I believe, you are looking to get Keys for those items where there is a pair of string available in Values . 我相信,您正在寻找在Values中有一对可用字符串的那些项目的Keys

var result  = myDict.GroupBy(r => r.Value)
                    .Where(grp => grp.Count() == 2)
                    .SelectMany(grp => grp.Select(subItem => subItem.Key))
                    .ToList();

If you want to get keys for those items which have multiple string values, (more than two) then modify the condition to: 如果要获取具有多个字符串值(大于两个)的项的键,则将条件修改为:

.Where(grp => grp.Count() >= 2)

Another thing to add, you are adding keys as Random values in the dictionary. 要添加的另一件事是,您要在字典中将键作为Random值添加。 Remember, Random doesn't mean Unique . 请记住, Random并不意味着Unique You could end up with an exception since Dictionary keys are unique. 由于Dictionary键是唯一的,因此您可能最终会遇到异常。

If your dictionary is defined as: 如果您的字典定义为:

Dictionary<double, string> myDict = new Dictionary<double, string>
{
    {1, "ABC"},
    {2, "ABC"},
    {3,"DEF"},
    {4,"DEF"},
    {5,"DEF2"},
    {6,"XYZ"}
};

For output after the LINQ expression: 对于LINQ表达式之后的输出:

foreach (var d in result)
{
    Console.WriteLine(d);
}

Output: 输出:

1
2
3
4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM