1

This is my function where I created a dictionary:

public int Scale(string value)
{
 //some calculs
 int result = 19; // or int between 0 and 40
 this.stringToInt = new Dictionary<string, int>()
 {
  {"1p",00},{"2p",01},{"3p",03} ... {"300p",40}
 };
// Here I try to do something like that: if(result == (int in dictionary) return associate string
}

I tried the below code:

if (this.stringToInt.ContainsValue(result)
{
    return this.stringToInt[result]; // I don't know what to write between hook (result doesn't work).
}

I don't know how to return associate string.

Thank you in advance for help!

LopDev
  • 823
  • 10
  • 26
  • 1
    You have to swap your int and string in your Dictionary ```new Dictionary``` and than use ```.ContainsKey()``` – nanu_nana Jun 25 '20 at 07:10
  • 1
    If @nanu_nana suggestion does not work (if the int values are not unique), you could use a simple linq: return stringToInt.First(x=> x.Value == result).Key. However if they are not unique you would get the first string key that matches. Ideally the use of ContainsKey is the best solution if applicable. – Claudiu A Jun 25 '20 at 07:14
  • 3
    Ultimately, this is using a dictionary **backwards**. If you need to do this very occasionally for modest size sets, fine - but if you need to do this often, or for very large data: you should consider having two dictionaries - one in each direction – Marc Gravell Jun 25 '20 at 07:18
  • 1
    @nanu_nana or `TryGetValue` – Marc Gravell Jun 25 '20 at 07:18
  • 2
    It seems there is no "the" direction for your searches. In [this question](https://stackoverflow.com/questions/62550548/c-sharp-comparaison-between-dictionarystring-int-and-value-in-enter) you´re searching for value by key, and here you´re searching for key by value. So chances are you need some new datastructure, where the keys are a combination of both your key and the value and compute the hashes based on both. – MakePeaceGreatAgain Jun 25 '20 at 07:24

1 Answers1

1
var keyValuePair = this.stringToInt.FirstOrDefault(x => x.Value == result);
if (!keyValuePair.Equals(new KeyValuePair<string, int>()))
{
    // found, use keyValuePair.Key
}

This would work i guess using Linq. But only returns the first found value. If the value is more than once in the dictionary, only the first one found is returned.

But you should do it like in the comment from @nanu_nana

hoffmanuel
  • 403
  • 1
  • 5
  • 14
  • It should be noted that this is a linear search through the dictionary, as if it were a plain list. Any performance advantages a dictionary would normally buy you go out the window this way. – Timo Jun 25 '20 at 07:42