Reputation: 87
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.
Upvotes: 4
Views: 2851
Reputation: 33381
If you need dictionary which holds one value per key you can use this:
var dict1 = lines
.Select(l => l.Split('|'))
.GroupBy(s => s[0])
.ToDictionary(d => d.Key, d => d.First()[1]);
or you can use this, if you want Dictionary<string,IEnumerable<string>>
which holds keys and corresponding values as IEnumerable<string>
var dict2 = lines
.Select(l => l.Split('|'))
.GroupBy(s => s[0])
.ToDictionary(d => d.Key, d => d.Select(r => r[1]));
Upvotes: 0
Reputation: 180917
You could always just use GroupBy
to create a group per key, and just pick the first value per key to the dictionary;
var dict = lines.Select(x => x.Split('|'))
.GroupBy(x => x[0], x => x[1])
.ToDictionary(x => x.Key, x => x.First());
Upvotes: 3
Reputation: 499002
Do not use ToDictionary
but a regular foreach
and test the keys.
Break the query from the conversion to a dictionary.
var splits = lines.Select(l => l.Split('|'));
var dict = new Dictionary<string,string>();
foreach(var item in splits)
{
if(!dict.ContainsKey(item[0]))
dict.Add(item[0], item[1]);
}
Upvotes: 5