在给定属于Value类型的属性的情况下,如何从Dictionary <Key,Value>获取单个值

Dre*_*rew 0 .net c# linq lambda dictionary

假设我有这本字典:

Dictionary<Guid, Person> people = new Dictionary<Guid, Person>();
Run Code Online (Sandbox Code Playgroud)

假设其中填充了一些数据。我们也说Person有一个Ssn属性。我想在人与回报的人Ssn = socialSecurityNum,其中socialSecurityNum一些价值。这是我要做的最好的主意:

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

我知道每个人都有不同的Ssn,所以我只返回列表中第一个值(因为列表只是一个值)。否则返回null。

我对此解决方案不满意的是,我必须从linq查询中获取一个列表,而不是单个值。是否有可以从字典中获取单个值的linq查询?

Kir*_*huk 5

代替Where使用FirstOrDefault

return people.Values.FirstOrDefault(p => p.SSN == socialSecurityNum);
Run Code Online (Sandbox Code Playgroud)