简体   繁体   中英

extract information from a dictionary

I have a dictionary where keys are product codes and values below each keys are some specifics of the products (eg weight, colour, price, etc.). Now let's say that the code loops through a list of product codes that I have. I want to check that the code (called myKey in the code below) is in my dictionary, in which case I also want to extract some properties (let's say just colour and price in my case). I am trying the following but without success:

var myColour = myDictionary
    .Where(x => myDictionary.Keys.Contains(myKey))
    .Select(x => x.Value.Colour);

var myPrice = myDictionary
    .Where(x => myDictionary.Keys.Contains(myKey))
    .Select(x => x.Value.Price);

I don't have any error, but I simply don't see the results stored in the variables myColor and myPrice.

What is the right syntax for my problem?

You seem to be over complicating things. The following should do what you want.

if (myDictionary.ContainsKey(myKey))
{
    var theValue = myDictionary[myKey].SomeProperty
}
MyValueType myValue;
if(myDictionary.TryGetValue(myKey, out myValue)){
    Console.Out.WriteLine(myValue.Colour);
    Console.Out.WriteLine(myValue.Price);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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