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];
    console.writeline("key not present");

you should achieve the effect that you want.


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.


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.


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;

Related Query

More Query from same tag