opt
opt

Reputation: 477

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 (e.g. 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?

Upvotes: 2

Views: 114

Answers (2)

Brian Reischl
Brian Reischl

Reputation: 7321

MyValueType myValue;
if(myDictionary.TryGetValue(myKey, out myValue)){
    Console.Out.WriteLine(myValue.Colour);
    Console.Out.WriteLine(myValue.Price);
}

Upvotes: 7

Steve
Steve

Reputation: 3061

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

if (myDictionary.ContainsKey(myKey))
{
    var theValue = myDictionary[myKey].SomeProperty
}

Upvotes: 8

Related Questions