0

I have dictionary created as

Dictionary<string, string> delta = new dictionary<string, string>();
        delta.Add("A", "One");
        delta.Add("B", "Two");
        delta.Add("C", "Three");

I wanted to retrieve value based on the value passed as key

public string GetValuefromdictionary(string roll. Dictionary<string, string> delta)
{       
    string rollValue;
    return rollValue = delta
        .Where(d => d.Key.Contains(roll))
        .Select(d =>   d.Value)
        .ToString();
}

however I am seeing it doesn't return me the string and I get like this

System.Linq.Enumerable+WhereSelectEnumerableIterator``2[System.Collections.Generic.KeyValuePair``2[System.String,System.String],System.String]

any help

Ivan Gritsenko
  • 4,166
  • 2
  • 20
  • 34
raj
  • 33
  • 1
  • 5

3 Answers3

0

if a Key is "ABC", and you pass "A" as roll, and you want to return the value from "ABC" because "ABC" contains "A". You can do this:

  return delta.FirstOrDefault(d=> d.Key.Contains(roll)).Value;
George
  • 777
  • 7
  • 17
0

Two options, better I would say two cases.

Case 1

Let's say Dictionary Values are unique, in this case we can simply transpose the dictionary swapping <Key,Value> pair.

var transformDictionary = delta.ToDictionary(kp => kp.Value, kp => kp.Key);

Now we can access this like any other dictioanry.

transformDictionary["One"];

Case 2 :

Values are not unique, in this case use LookUp.

var lookup = delta.ToLookup(c=>c.Value, c=>c.Key);      
var lookupvalue = ((IEnumerable<string>)lookup["One"]).First();

Working Demo

Hari Prasad
  • 16,716
  • 4
  • 21
  • 35
-1

You want to search for an element in a Dictionary, but using value instead of > a key. So you iterate through you dictionary and return the first element that has the value you are looking for. The output you get is a keyValue pair, hence the .Key

string key = "One";
string value = delta.FirstOrDefault(d => d.Value.Contains(key)).Key;
Renuka Deshmukh
  • 998
  • 9
  • 16