score:14

Accepted answer

It really does seem like you're overcomplicating this issue.

You can just use the indexer ([]) of the Dictionary class along with the .ContainsKey() method.

If you use something like this:

string value;
if (myDict.ContainsKey(key))
{
    value = myDict[key];
}
else
{
    Console.WriteLine("Key Not Present");
    return;
}

You should achieve the effect that you want.

score:13

If you want to retrieve a value of a key from a dictionary access by indexer or TryGetValue:

var value = listaFirme[matchKey];

//If you don't know for sure that dictionary contains key
string value;
if(a.TryGetValue(matchKey, out value))
{
    /* Code here */
}

As for why you got the result you did: Linq operations of Where and Select return an IEnumerable<T> so when doing ToString on it it executes the ToString of IEnumerable which is to print it's type.

Notice that listaFirme isn't a good name for a dictionary


If you did not have a dictionary and wanted to return one item then you'd use FirstOrDefault:

var value = someList.FirstOrDefault(item => /* some predicate */)?.Value;

score:0

Replace toString(); with FirstOrDefault();

When you are applying .Where() condition it will return an Enumerable. You have to either cast it to list using .ToList() then you will get list of the values that meet the condition you used, or if you just want to get the first one you can use FirstOrDefault();

You can also write it like this

listaFirme.FirstOrDefault(pair => pair.Key == matchKey).Value

Since FirstOrDefault() accepts a predicate, you don't need always need to use .Where.

score:3

It seems that you've overcomplicated the usage. In this case you don't need Linq. Just use the Dictionary provided indexer: listaFirme[matchKey]. This returns the related value. IF the key does not exist the Dictionary throws a KeyNotFoundException exception. If you want to check if the key exists you can use the ContainsKey() method which returns a bool.


Related Articles