How do I execute a LINQ query against a dictionary?
I have a dictionary that contains identifiers like the name of a string and cities, as well as a string. I want to find a city by its name and return ID. There my code:
public string GetIdByCityName(string name)
{
if (Cities.ContainsValue(name))
{
return Cities
.Select(x => x)
.Where(v => v.Value == name)
.Select(k => k.Key)
.ToString();
}
else
{
return string.Empty;
}
}
Cities are, of course, my vocabulary. I have a problem because this code doesn't work. I tried using a debugger and I found what value was returned from the method:
System.Linq.Enumerable + WhereSelectEnumerableIterator 2 [System.Collections.Generic.KeyValuePair 2 [System.String, System.String], System.Boolean]
What am I doing wrong?
source to share
You see this result because it .Select(k => k.Key)
is a LINQ query that has a type WhereSelectEnumerableIterator
. It is not one line. When you apply ToString()
to a query type, you see the type name.
You can select the first entry that matches the given name:
return Cities.Where(kvp => kvp.Value == name).Select(kvp => kvp.Key).FirstOrDefault();
Note: several cities may have the same name. Also you don't need to do .Select(x => x)
because it implements an entrance to itself.
source to share
Shortest code (and arguably easier to read):
return Cities.FirstOrDefault(_ => _.Value == name).Key;
Simplified method
Your method can also be simplified to
public string GetIdByCityName(string name)
{
return Cities.ContainsValue(name) ?
Cities.FirstOrDefault(_ => _.Value == name).Key : String.Empty;
}
or if you are using C # 7 you can do this fancy thing ( null constraint operator )
string GetIdByCityName(string name)
{
return Cities.FirstOrDefault(_ => _.Value == name).Key ?? String.Empty;
}
source to share