Reputation: 10738
I have an array that I want to convert to a dictionary by splitting the array values from the equal sign (=
). The content before the equal sign will be the key and the content after it will be the value. My issue is that some values from the array will have the same key name when splitting it and adding them to the dictionary.
Here is what I have...
string[] myArray = new[] { "A=1", "B=2", "C=3", "A=4" };
Dictionary<string, string> myDictionary = myArray.Select(l => l.Split('=')).ToDictionary(a => a[0], a => a[1]);
As expected, I get error: ArgumentException was unhandled by user code
since the first and the last value will have the same keys.
What I would like to be able to do is exclude/ignore the values that will generate duplicate keys. In other words, based on my code I don't want to add the value A=4
to my dictionary.
Any idea what would be the best way to accomplish this?
FYI - My code works fine if I remove the last value from the array.
Upvotes: 2
Views: 70
Reputation: 56423
using GroupBy
before ToDictionary
:
var result = myArray.Select(s => s.Split('='))
.GroupBy(a => a[0])
.ToDictionary(e => e.Key,
v => v.Select(a => a[1]).First());
or iterating and checking if the key is not contained in the result dictionary:
Dictionary<string, string> accumulator = new Dictionary<string, string>();
foreach (var item in myArray.Select(x => x.Split('=')))
if (!accumulator.ContainsKey(item[0]))
accumulator.Add(item[0], item[1]);
Upvotes: 2
Reputation: 10839
Use the below code, which converts the given array to unique dictionary. The GroupBy
, groups the data based on left side of Key and later ToDictionary
converts the fetched grouped result to dictionary.
Dictionary<string, string> myDictionary = myArray.Select(l =>
{
var splittedStrings = l.Split('=');
return new { Key = splittedStrings[0], Val = splittedStrings[1] };
}).GroupBy(g => g.Key)
.ToDictionary(a => a.Key, a => a.First().Val);
Upvotes: 1
Reputation: 34152
You may use GroupBy , and group the splitted values by it's first value (index 0), and then get first of each group (ignore others with same value in the index 0):
var myArray.Select(l => l.Split('=')).GroupBy(x=>x[0]).Select(x=>x.FirstOrDefault());
Or just do the ignore part when adding to Dictionary:
foreach(string[] x in myArray.Select(l => l.Split('=')).ToArray())
{
if(!Dic.ContainsKey(x[0]))Dic.Add(x[0], x[1]);
}
Upvotes: 1