Linq on dictionary c #

0

I'm trying to make a linq on a dictionary to find a key, I have something like this, and I want to find the value of the "Hello" key:

Dictionary<int, Dictionary<string, string> Datos = new Dictionary<int, Dictionary<string, string>>();
Dictionary<string, string> Dato = new Dictionary<string, string>();
Dato.Add("Hola","Mundo");
Datos.Add(1,Dato);
    
asked by GHerreraZ 21.05.2018 в 15:46
source

1 answer

1

If you are looking for the Data key that contains the dictionary with the "Hello" key:

var query = (from x in Datos
             where x.Value.Keys.Contains("Hola")
             select x.Key).FirstOrDefault();

Or if you like more in fluent version:

var query = Datos
    .Where(x => x.Value.Keys.Contains("Hola"))
    .Select(x => x.Key)
    .FirstOrDefault();

If, on the contrary, if you are looking for the value of the dictionary Dato that contains the "Hello" key, you do not occupy Linq:

var key = Dato["Hola"];

or if you are not sure there is a "Hello" key:

string valor;
if (Dato.TryGetValue("Hola", out valor))
{
    // aquí puedes usar valor
}
    
answered by 21.05.2018 в 17:20