Reputation: 209
var listaFirme = new Dictionary<string, string>
{
{ "foo", "bar" }
};
var matchKey = "foo";
return listaFirme.Where(pair => pair.Key == matchKey).Select(pair => pair.Value).ToString();
I know that the keys are unique, so I want to return one value from my Dictionary. In this case it doesn't work, as it returns the string "System.IEnumerable<String>"
...
Upvotes: 8
Views: 94180
Reputation: 6134
Works far better as an expression instead of an if-else statement:
listaFirme.TryGetValue(matchKey, out var value) ? value : null
Upvotes: 0
Reputation: 4806
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 val;
if (myDict.ContainsKey(key))
{
val = myDict[key];
}
else
{
Console.WriteLine("Key Not Present");
return;
}
You should achieve the effect that you want.
Upvotes: 21
Reputation: 37299
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;
Upvotes: 14
Reputation: 2908
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
.
Upvotes: 4
Reputation: 2318
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
.
Upvotes: 0