leora leora - 6 months ago 29
C# Question

Convert list to dictionary using linq and not worrying about duplicates

I have a list of Person objects. I want to convert to a Dictionary where the key is the first and last name (concatenated) and the value is the Person object.

The issue is that I have some duplicated people, so this blows up if I use this code:

private Dictionary<string, Person> _people = new Dictionary<string, Person>();

_people = personList.ToDictionary(
e => e.FirstandLastName,

I know it sounds weird but I don't really care about duplicates names for now. If there are multiple names I just want to grab one. Is there anyway I can write this code above so it just takes one of the names and doesn't blow up on duplicates?

Answer Source

Here's the obvious, non linq solution:

foreach(var person in personList)
    myDictionary.Add(person.FirstAndLastName, person);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download