Given
string[] array = new string[]
{
"Sample1:foo",
"Sample2:bar",
"Sample1:foo1"
}
I know I can convert it to a dictionary this way:
Dictionary<string, string> whatever = new Dictionary<string, string>
foreach (string s in array) do...
string sampleNumber = s.Substring(0, indexOfColon);
string fooOrBar= s.Substring(indexOfColon + 1);
whatever[sampleNumber] = fooOrBar;
And this will prevent an aggregate exception being thrown when a duplicate key is added (although overriding the key, which is fine in this case). Can I do this with LINQ? I am trying something along the lines of:
Dictionary<string, string> whatever = array.ToDictionary(
key => key.Split(':')[0], value => value.Split(':')[1]);
Is there a way to do this without creating a lookup beforehand?
Try this:
Dictionary<string, string> whatever =
array
.Reverse()
.GroupBy(key => key.Split(':')[0])
.SelectMany(x => x.Take(1))
.ToDictionary(key => key.Split(':')[0], value => value.Split(':')[1]);
It gives:

Or you could do this:
Dictionary<string, string> whatever =
array
.Aggregate(
new Dictionary<string, string>(),
(d, v) => { d[v.Split(':')[0]] = v.Split(':')[1]; return d; });
Same result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With