I have simple LINQ statement which splits a string and then throws the values into a dictionary. The problem is that rarely the dictionary already has an existing key of the same value so an exception is thrown and the the value of “dict” remains empty.
dict = lines.Select(l => l.Split('|')).ToDictionary(d => d[0], d => d[1]);
Is there a way to modify the LINQ statement to check if the dictionary already has the key before inserting it or to catch the exception but continue writing the rest of the values into the dictionary? I tried putting a try block around the line and it catches the exception but results in no elements being added so the dictionary remains empty.
Do not use
ToDictionarybut a regularforeachand test the keys.Break the query from the conversion to a dictionary.