Drew Drew - 2 months ago 6
C# Question

How to get a single value from a Dictionary<Key,Value> given a property that belongs to the type Value

Let's say I have this dictionary:

Dictionary<Guid, Person> people = new Dictionary<Guid, Person>();


Assume it's populated with some data. Let's also say
Person
has a
Ssn
property. I would like to return the Person in people with
Ssn = socialSecurityNum
where
socialSecurityNum
is some value. This is the best idea I have to do this:

public Person GetPerson(int socialSecurityNum)
{
IEnumerable<Person> persons = people.Values.Where(p => p.SSN == socialSecurityNum);
foreach (Person person in persons)
{
return person;
}
return null;
}


I know that each person will have a different
Ssn
, so I just return whatever value is first in the list (since the list is just one value). Otherwise return null.

The thing I don't like about this solution is that I have to get a list from the linq query as opposed to a single value. Is there a linq query that can get a single value from the dictionary?

Answer

Instead of Where use FirstOrDefault

return people.Values.FirstOrDefault(p => p.SSN == socialSecurityNum);